Reverse Vowels of a String (LeetCode 345): Solution and Explanation

Easy
Two Pointers
String

Given a string, reverse the order of its vowels (a, e, i, o, u in either case) while every other character stays at its index. Return the resulting string.

Intuition

One way is to collect the vowels into a list, reverse the list, and then walk the string again, replacing each vowel with the next one from the reversed list. That is correct and linear, but it takes two passes and an extra list.

Look at what reversal does to a sequence: the first element trades places with the last, the second with the second to last, and so on until the middle. Here the sequence is just the vowels, spread out among consonants that never move.

So place one pointer at each end of the string. Each pointer slides inward over consonants until it lands on a vowel. When both are on vowels, those two are exactly the outermost pair still unswapped, so swap them and step both pointers inward. When the pointers meet or cross, every pair has been swapped once.

Each pointer only ever moves toward the middle, so together they touch each character at most once.

Approach: Two pointers that stop on vowels

  1. Build a set of the ten vowel characters (lower and upper case).
  2. Copy the string into a character array and set left = 0, right = n - 1.
  3. While left < right: if chars[left] is not a vowel, increment left.
  4. Otherwise, if chars[right] is not a vowel, decrement right.
  5. Otherwise both are vowels: swap them, then increment left and decrement right.
  6. Join the array back into a string and return it.

Step-by-step example

s = "IceCreAm"
  1. left = 0 is on 'I', a vowel. right = 7 is on 'm', not a vowel, so right moves to 6.
  2. right = 6 is on 'A'. Swap 'I' and 'A', giving "AceCreIm". The pointers move to 1 and 5.
  3. left = 1 is 'c', so it moves to 2, which is 'e'. right = 5 is 'e' already.
  4. Swap 'e' and 'e' (no visible change) and move to 3 and 4.
  5. left = 3 is 'C', so it moves to 4. Now left equals right, so the loop ends.
  6. The answer is "AceCreIm".

Code: Python, Java, C++

1class Solution:
2    def reverseVowels(self, s: str) -> str:
3        vowels = set('aeiouAEIOU')
4        chars = list(s)
5        left, right = 0, len(chars) - 1
6        while left < right:
7            if chars[left] not in vowels:
8                left += 1
9            elif chars[right] not in vowels:
10                right -= 1
11            else:
12                chars[left], chars[right] = chars[right], chars[left]
13                left += 1
14                right -= 1
15        return ''.join(chars)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every iteration moves at least one pointer inward, so there are at most n iterations, each with an O(1) set lookup.

Space

O(n)

The character array is a copy of the string. In C++, where strings are mutable, the extra space is O(1).

Other approaches

Collect, reverse, refill (time O(n), space O(n))

Gather the vowels in a list, reverse it, then rebuild the string, taking the next reversed vowel at each vowel position. Easy to get right, but it uses a second pass and a second buffer.

Stack of vowels (time O(n), space O(n))

Push every vowel onto a stack on the first pass, then pop one at each vowel position on the second pass. Popping returns them in reverse order. Same cost as collect and reverse.

Common mistakes

  • Forgetting upper-case vowels. 'A' and 'a' are both vowels, and the input can mix them.
  • Using nested while loops for skipping without re-checking left < right inside them, which can run a pointer off the end of a string that has no vowels.
  • Building the result with += on an immutable string inside the loop, which can turn the solution quadratic in languages like Java.
  • Treating 'y' as a vowel. This problem only counts a, e, i, o and u.

Frequently asked questions

Why does swapping from the outside in reverse the vowels?

Reversing a sequence of length m swaps element k with element m - 1 - k for every k below the middle. The left pointer meets vowels in order k = 0, 1, 2 and the right pointer meets them in order m - 1, m - 2, so each swap is exactly one of those pairs.

What happens when the string has no vowels?

The left pointer skips every character until it reaches the right pointer, the loop ends, and the string is returned unchanged.

Is the swap of two equal vowels a problem?

No. Swapping 'e' with 'e' changes nothing, and both pointers still move inward, so the loop keeps making progress.