Reverse Vowels of a String
(#345), Easy
Category: String, Two Pointer
Problem Statement
Given a string s, reverse only the vowels of the string. Vowels include a, e, i, o, u (both uppercase and lowercase).
Examples
Input: s = "leetcode"
Output: "leotcede"
Explanation: Only vowels 'e', 'e', 'o', 'e' are reversed.
Input: s = "hello"
Output: "holle"
Explanation: Vowels 'e' and 'o' are swapped.
Input: s = "IceCreAm"
Output: "AceCriEm"
Explanation: Multiple vowels are reversed using two-pointer logic.
Input: s = "AEIOU"
Output: "UOIEA"
Explanation: All vowels reversed completely.
Approach
Two Pointer Approach
- Convert the string into a character array for easy manipulation.
- Initialize two pointers: one at the start and one at the end of the array.
- Use a Set to store all vowels (both uppercase and lowercase).
- Move the pointers inward while skipping non-vowel characters.
- When both pointers are at vowels, swap the characters.
- Continue this process until the two pointers meet.
- Finally, join the array back into a string and return it.
var reverseVowels = function (s) {
const vowels = new Set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]);
const chars = s.split("");
let start = 0;
let end = s.length - 1;
while (start < end) {
while (start < end && !vowels.has(chars[start])) start++;
while (start < end && !vowels.has(chars[end])) end--;
[chars[start], chars[end]] = [chars[end], chars[start]];
start++;
end--;
}
return chars.join("");
};
Complexity
Time: O(n)
Space: O(n)