Reverse Vowels of a String(#345)
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"
Input: s = "hello"
Output: "holle"
Input: s = "IceCreAm"
Output: "AceCriEm"
Input: s = "AEIOU"
Output: "UOIEA"
๐ง Approach
We use the **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 until the pointers meet.
โข Finally, join the character array back into a string and return it.
This approach allows us to reverse only the vowels efficiently in O(n) time and O(n) space.
๐ป Code
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)