Reverse Vowels of a String

Easy · Two Pointers · Explanation and code example

Two Pointers on Vowels

How it works

Advance a left pointer and a right pointer past consonants until both point at vowels. Swapping those vowels reverses only the vowel sequence, preserving all other characters at their original positions. Continue until the pointers meet.

Steps

  1. Find the next vowel from each end.
  2. Swap them and advance both pointers.
  3. Return the resulting character sequence.

Complexity

  • Time: O(n).
  • Space: Python O(n) for a mutable character list; C++ uses the O(n) by-value string buffer.

Things to watch for

  • Uppercase vowels count too.
  • A string with no vowels remains unchanged.
  • Check pointer bounds while skipping consonants.

Python code example

class Solution:
  def reverseVowels(self, s: str) -> str:
    chars = list(s)
    VOWELS = 'aeiouAEIOU'
    l = 0
    r = len(s) - 1

    while l < r:
      while l < r and chars[l] not in VOWELS:
        l += 1
      while l < r and chars[r] not in VOWELS:
        r -= 1
      chars[l], chars[r] = chars[r], chars[l]
      l += 1
      r -= 1

    return ''.join(chars)

C++ code example

class Solution {
 public:
  string reverseVowels(string s) {
    int l = 0;
    int r = s.length() - 1;

    while (l < r) {
      while (l < r && !isVowel(s[l]))
        ++l;
      while (l < r && !isVowel(s[r]))
        --r;
      swap(s[l++], s[r--]);
    }

    return s;
  }

 private:
  bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiouAEIOU";
    return kVowels.find(c) != string_view::npos;
  }
};
Source and license

Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations