Reverse Vowels of a String (LeetCode 345): Solution and Explanation
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
- Build a set of the ten vowel characters (lower and upper case).
- Copy the string into a character array and set
left = 0,right = n - 1. - While
left < right: ifchars[left]is not a vowel, incrementleft. - Otherwise, if
chars[right]is not a vowel, decrementright. - Otherwise both are vowels: swap them, then increment
leftand decrementright. - Join the array back into a string and return it.
Step-by-step example
s = "IceCreAm"
left = 0is on 'I', a vowel.right = 7is on 'm', not a vowel, sorightmoves to 6.right = 6is on 'A'. Swap 'I' and 'A', giving "AceCreIm". The pointers move to 1 and 5.left = 1is 'c', so it moves to 2, which is 'e'.right = 5is 'e' already.- Swap 'e' and 'e' (no visible change) and move to 3 and 4.
left = 3is 'C', so it moves to 4. Nowleftequalsright, so the loop ends.- 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)1class Solution {
2 public String reverseVowels(String s) {
3 String vowels = "aeiouAEIOU";
4 char[] chars = s.toCharArray();
5 int left = 0, right = chars.length - 1;
6 while (left < right) {
7 if (vowels.indexOf(chars[left]) < 0) {
8 left++;
9 } else if (vowels.indexOf(chars[right]) < 0) {
10 right--;
11 } else {
12 char tmp = chars[left];
13 chars[left] = chars[right];
14 chars[right] = tmp;
15 left++;
16 right--;
17 }
18 }
19 return new String(chars);
20 }
21}1class Solution {
2public:
3 string reverseVowels(string s) {
4 string vowels = "aeiouAEIOU";
5 int left = 0, right = (int)s.size() - 1;
6 while (left < right) {
7 if (vowels.find(s[left]) == string::npos) {
8 left++;
9 } else if (vowels.find(s[right]) == string::npos) {
10 right--;
11 } else {
12 swap(s[left], s[right]);
13 left++;
14 right--;
15 }
16 }
17 return s;
18 }
19};Time and space complexity
O(n)
Every iteration moves at least one pointer inward, so there are at most n iterations, each with an O(1) set lookup.
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 < rightinside 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.