15% off all plans & roadmaps Use code
See plansReverse Vowels of a String
- LeetCode 345
- Easy
- Two Pointers
- String Reversal
Updated
TL;DR: Reverse only the vowels in a string and leave every other character in place. Walk two pointers inward from both ends, skip anything that is not a vowel, and swap each vowel pair you find.
Problem
Given a string s, reverse only the vowels in it and return the result.
The vowels are 'a', 'e', 'i', 'o', and 'u'. They can appear in both lower and upper case, and more than once.
Example 1
Input: s = "IceCreAm" Output: "AceCreIm" Explanation: The vowels in s are ['I', 'e', 'e', 'A']. Reversing them gives "AceCreIm".
Example 2
Input: s = "leetcode" Output: "leotcede"
Constraints
1 <= s.length <= 3 * 10^5sconsists of printable ASCII characters.
Constraints that matter
- A length of 3 * 10^5 rules out any approach that scans the string once per vowel, which would be O(n^2).
- Printable ASCII means a 128-entry lookup or a small set is enough for the vowel check, so each check costs O(1).
- Vowels appear in both cases, so the vowel set must contain all ten letters or uppercase vowels will stay put.
- Consonants never move, so you only need to track positions of vowels, not rebuild the whole string from scratch.
Hints
Hint 1
This is a two pointers problem on a string.
Hint 2
The naive plan separates two jobs.
Solution
Intuition
This is a two pointers problem on a string. The vowels move, and everything else stays where it is. The first vowel swaps with the last vowel, the second with the second to last, and so on. That pairing runs from the outside in, which is the shape two pointers handles well.
Picture two people walking toward each other along a row of cups, skipping any cup that is not a vowel cup. The two walkers are the left and right pointers, and the vowel cups are the only things they ever swap.
What to notice is that you only care about vowels. A left pointer walks right past consonants until it lands on a vowel. A right pointer walks left the same way. When both stop on vowels and they have not crossed, those two positions form a pair that must trade places.
Why this works: each pointer moves in one direction and never goes back. The pairs are visited in the order the reversal needs. After a swap, both pointers move one step inward and search for the next pair.
Worked example
Input: s = "Programming is fUn!" Output: "PrUgrimming as fon!" Explanation: The vowels in order are o, a, i, i, U. Reversing that order puts U at index 2, i at index 5, i at index 8, a at index 12, and o at index 16. Consonants, spaces, and the exclamation mark do not move.
Approach 1: Brute force: collect, then write back
The naive plan separates two jobs. First you collect every vowel in a list, then you write them back into the vowel positions in reverse order. A beginner reaches for this because it is easy to check.
The cost is two full passes over the string and a list that can hold n characters. The list exists only because the answer is written from left to right, while the vowels must be read from right to left.
Steps
- Create an empty list and walk
sfrom left to right. Append each vowel you see. - Copy
sinto a buffer that you can change. - Walk the buffer from left to right again. At each vowel position, take the last unused vowel from the list.
- Leave consonants, digits, spaces, and symbols as they are.
- Join the buffer into a string and return it.
Dry run
Start with Programming is fUn!. The first pass collects the vowels in order: o, a, i, i, U. The list is now [o, a, i, i, U].
The second pass visits the vowel positions 2, 5, 8, 12, and 16. At each one it takes the last item of the list.
- Index 2 takes U, so the buffer has U there.
- Index 5 takes i.
- Index 8 takes i.
- Index 12 takes a.
- Index 16 takes o.
The buffer now reads PrUgrimming as fon!, which is the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. The first loop reads each character once, and the second loop reads each character once, so the work is about 2n constant-time steps, which is O(n). Each vowel check is a set or table lookup that costs O(1). The list holds at most n vowels and the buffer holds n characters, so the extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set('aeiouAEIOU')
found = [c for c in s if c in vowels]
chars = list(s)
for i in range(len(chars)):
if chars[i] in vowels:
# pop() takes the last vowel first
chars[i] = found.pop()
return ''.join(chars)The String Reversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
String Reversal
Part of Two Pointers
Approach 2: Two pointers from both endsOptimalString Reversal
The first approach repeats work. It reads the string twice and stores every vowel, even though each vowel has a partner that is known as soon as you find it. The list is only needed because the first vowel is written before the last one is read.
The insight that fixes this is that the left and right pointers can find each swap pair directly. Each pair is swapped in the copy as soon as both ends are found, so one pass is enough and no list is needed.
Keep left at the start and right at the end. Move left forward past non-vowels and right backward past non-vowels. When both stop on vowels and left is still less than right, swap them and move both inward. Stop when the pointers meet or cross.
Python, Java, JavaScript, Go, and C# strings cannot change in place. The first step copies the string into an array of characters. C++ can edit the string it receives.
Why it is correct. Every vowel outside the two pointers has already been swapped with its mirror, so the vowels are in reversed order. Non-vowels never move, so skipping them loses nothing. Each swap pairs the nth vowel from the left with the nth from the right, which is exactly what reversal requires.
Steps
- Copy
sinto a mutable array of characters. In C++ you can edit the string directly. - Set
leftto 0 andrightto the last index. - While
left < rightandchars[left]is not a vowel, add one toleft. - While
left < rightandchars[right]is not a vowel, subtract one fromright. - If
left < right, swap the two characters, then add one toleftand subtract one fromright. - Repeat the three steps above while
left < right. - Return the array as a string.
Dry run
Start with Programming is fUn!, with left = 0 and right = 18. Each row shows where the pointers stop and the buffer after the step.
| Step | Left stops at | Right stops at | Action | String after the step |
|---|---|---|---|---|
| 1 | index 2 (o) | index 16 (U) | Swap o and U | PrUgramming is fon! |
| 2 | index 5 (a) | index 12 (i) | Swap a and i | PrUgrimming as fon! |
| 3 | index 8 (i) | index 8 (i) | Pointers meet, no swap, loop ends | PrUgrimming as fon! |
In row 1, left skips P and r, and right skips ! and n. In row 2, left skips g and r, and right skips f, the space, and s.
In row 3, left skips m and m, and right skips the space, g, and n. Both pointers then rest on index 8, so the loop ends. The result is PrUgrimming as fon!, which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. The left pointer only moves forward and the right pointer only moves backward, and the loop ends when they meet. Together they move at most n times, and each character check costs O(1). The array copy takes O(n) space, and the two indices and one temporary value add O(1) more.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set('aeiouAEIOU')
# Strings are immutable in Python, so work on a list
chars = list(s)
left, right = 0, len(chars) - 1
while left < right:
# Skip consonants from the left
while left < right and chars[left] not in vowels:
left += 1
# Skip consonants from the right
while left < right and chars[right] not in vowels:
right -= 1
if left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return ''.join(chars)Common mistakes
while chars[left] not in vowelswithout theleft < rightguard. Once no vowels remain, the pointer runs past the other pointer or off the end. Putleft < rightin every inner loop.vowels = set('aeiou')with lowercase letters only. The problem allows uppercase vowels, soIceCreAmwould keepIandAin place. IncludeAEIOUin the set.- Forgetting to move both pointers after a swap. If
leftstays put, the same pair is swapped again on the next pass and the loop never ends. Add one toleftand subtract one fromrightafter every swap. s[left], s[right] = s[right], s[left]on a Pythonstr. Python strings are immutable, so this raises a TypeError. Convert to a list first and join at the end.found.pop(0)or readingfoundfrom the front in the brute force. Taking vowels in their original order puts each vowel back where it started, so the output equals the input. Take vowels from the end of the list.- Building the answer with
result += cin a loop in Java, Python, or C#. Each concatenation copies the whole string, so the loop costs O(n^2) in the worst case. Write into a char array or list and build the string once.
Edge cases
- A string with no vowels, such as
xyz. Both pointers skip everything, and the output equals the input. - A single character, such as
a. The outer loop never runs, and the output isa. - All vowels, such as
aeiou. Every position is swapped, and the output isuoiea. - A palindrome of vowels, such as
aba. The swap of indices 0 and 2 leaves the string unchanged, which is correct. - Mixed case, such as
hEllO. The output ishOllE, so uppercase vowels take part in the swap. - Maximum length, about 3 * 10^5, with all vowels. The loop does about n steps, so it runs in O(n) time within the limits.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Reverse Vowels of a String, with how to answer them.
Unlock the follow-upsReverse Vowels of a String FAQ
What is the time complexity of Reverse Vowels of a String?
The time complexity is O(n), where n is the length of the string. The two pointers move at most n steps in total, and each check takes constant time.
Why use two pointers for Reverse Vowels of a String?
The reversal pairs the first vowel with the last, the second with the second to last, and so on. Two pointers that start at both ends find each pair in order and swap it. That matches the pairing directly, with no list needed.
Can Reverse Vowels of a String be solved in O(1) extra space?
Yes, beyond the output, if the language lets you edit the string. In C++ the function already owns a copy, so the swaps use O(1) extra variables. In Python, Java, JavaScript, Go, and C#, a string cannot change, so the array copy costs O(n) and cannot be avoided.
Why does the Python solution convert the string to a list?
Python strings are immutable, so s[i] = c raises a TypeError. A list of characters supports O(1) swaps. Call ''.join at the end to turn the list back into a string.
Does the problem count uppercase vowels as vowels?
Yes. The vowels are a, e, i, o, u and their uppercase forms. Put all ten characters in the set, so that A is found as a vowel and swapped like any other vowel.
Asked at
See which companies ask this — Pro
Related problems
- Reverse String · same technique: String Reversal
- Reverse String II · same technique: String Reversal
- Reverse Integer · same technique: String Reversal
- Reverse Words in a String · same technique: String Reversal
- Happy Number · same pattern: Two Pointers
- Linked List Cycle · same pattern: Two Pointers
- Remove Duplicates from Sorted Array · same pattern: Two Pointers
- Remove Element · same pattern: Two Pointers
- Merge Strings Alternately · same pattern: Two Pointers
- Move Zeroes · same pattern: Two Pointers