Reverse Vowels of a String
Given a string s, reverse only the vowels of the string, leaving all other characters in their original positions. Vowels are 'a', 'e', 'i', 'o', 'u' and their uppercase forms. Use two pointers starting at the left and right ends, skipping non-vowel characters and swapping vowels as the pointers converge toward the middle.
Constraints
- 1 ≤ s.length ≤ 3 × 105
- s consists of printable ASCII characters
Example
s = "hello""holle"Explanation The vowels e and o swap positions while h, l, l stay in place.
Converge two pointers, swapping vowels as they meet
left skips index 0 ('h', not a vowel) and lands on index 1 ('e'). right lands on index 4 ('o'). Both are vowels — about to swap.
What happens in this step
left skips index 0 ('h', not a vowel) to land on index 1 ('e')
right = 4 (value 'o'), already a vowel
Both left and right sit on vowels, so they are about to swap.Steps to visualize
- Place one pointer at the start and one at the end of the string.
- Move the left pointer right while it sits on a non-vowel.
- Move the right pointer left while it sits on a non-vowel.
- Swap the vowels at both pointers, then move both one step toward the middle.
- Repeat until the pointers meet or cross.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
left skips index 0 ('h', not a vowel) and lands on index 1 ('e'). right lands on index 4 ('o'). Both are vowels — about to swap.
What happens in this step
left skips index 0 ('h', not a vowel) to land on index 1 ('e')
right = 4 (value 'o'), already a vowel
Both left and right sit on vowels, so they are about to swap.Solution
function reverseVowels(s) {
const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
const chars = s.split('');
let left = 0;
let right = chars.length - 1;
while (left < right) {
while (left < right && !vowels.has(chars[left])) {
left++;
}
while (left < right && !vowels.has(chars[right])) {
right--;
}
if (left < right) {
const temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
return chars.join('');
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
s = "hello" | "holle" | example from the docstring |
s = "xyz" | "xyz" | no vowels present, string is unchanged |
s = "aeiou" | "uoiea" | every character is a vowel |
s = "Aa" | "aA" | mixed case, adjacent vowels of different case |
s = "leetcode" | "leotcede" | vowels and consonants interleaved throughout the string |
s = "b" | "b" | smallest valid input, a single non-vowel character |
s = "ab" | "ab" | only one vowel present, nothing to swap with |