Reverse Vowels of a String

Reverse only the vowels of a string in place using two pointers, in O(n) time.

Problem Statement

Given a string s, reverse only the vowels (a, e, i, o, u in both cases) and return the result. All non-vowel characters stay in their original positions.

Example

Input:  s = "leetcode"
Output: "leotcede"
Explanation: The vowels e, e, o, e are reversed; consonants stay put.

Two Pointer Approach

Place pointers at both ends and move them toward each other. When both pointers sit on vowels, swap them; otherwise advance whichever pointer is not on a vowel.

Complexity

  • Time: O(n)
  • Space: O(n) for the character array (O(1) in languages with mutable strings)

Solution Code

Python

def reverseVowels(s):
    vowels = set("aeiouAEIOU")
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        if chars[left] not in vowels:
            left += 1
        elif chars[right] not in vowels:
            right -= 1
        else:
            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1
    return "".join(chars)

Java

String reverseVowels(String s) {
    String vowels = "aeiouAEIOU";
    char[] c = s.toCharArray();
    int left = 0, right = c.length - 1;
    while (left < right) {
        if (vowels.indexOf(c[left]) < 0) left++;
        else if (vowels.indexOf(c[right]) < 0) right--;
        else {
            char t = c[left]; c[left] = c[right]; c[right] = t;
            left++; right--;
        }
    }
    return new String(c);
}

C++

string reverseVowels(string s) {
    string vowels = "aeiouAEIOU";
    int left = 0, right = s.size() - 1;
    while (left < right) {
        if (vowels.find(s[left]) == string::npos) left++;
        else if (vowels.find(s[right]) == string::npos) right--;
        else { swap(s[left], s[right]); left++; right--; }
    }
    return s;
}

Key Takeaways

  • Only swap when both pointers are on vowels.
  • A set lookup keeps the vowel check at O(1).
  • Same opposite-direction pattern as Valid Palindrome, but with a swap step.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.