#345 - Reverse Vowels of a String
Given a string s, reverse only the vowels in the string and return it. The vowels are a, e, i, o, u (both lowercase and uppercase).
| Input | Output |
|---|---|
s = "hello" | "holle" |
s = "leetcode" | "leotcede" |
Given a string s, reverse only the vowels in the string and return it. The vowels are a, e, i, o, u (both lowercase and uppercase).
| Input | Output |
|---|---|
s = "hello" | "holle" |
s = "leetcode" | "leotcede" |
/**
* Reverses only the vowel characters in the string, preserving all other positions.
*
* @param s Input string (1 ≤ length ≤ 3 × 10⁵), ASCII only
* @returns String with vowels reversed
*/
export function reverseVowels(s: string): string {
const chars = s.split("");
const vowels = new Set("aeiouAEIOU");
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--;
[chars[left], chars[right]] = [chars[right], chars[left]];
left++;
right--;
}
return chars.join("");
}
Approach: two-pointer swap – use left and right pointers to find vowels from both ends and swap them until the pointers meet.
Time: O(n) – each pointer traverses the string at most once.
Space: O(n) – character array copy (required because strings are immutable in JS/TS).