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"

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

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)

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources