KatInterview

345. Reverse Vowels of a String

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to reverse the vowels within a given string while leaving all other characters, known as consonants, in their original positions. The vowels are 'a', 'e', 'i', 'o', 'u' and can appear in both lowercase and uppercase.

Solution

Reverse Vowels of a String in Python

class Solution:
    def reverseVowels(self, s: str) -> str:
        # Set for O(1) vowel lookup.
        vowels = set("aeiouAEIOU")
        # Python strings are immutable, convert to a list of characters.
        s_list = list(s)
        left, right = 0, len(s_list) - 1
        
        # Use two pointers to swap vowels from the ends.
        while left < right:
            # Find the first vowel from the left.
            while left < right and s_list[left] not in vowels:
                left += 1
            
            # Find the first vowel from the right.
            while left < right and s_list[right] not in vowels:
                right -= 1
            
            # If pointers have not crossed, swap the vowels.
            if left < right:
                s_list[left], s_list[right] = s_list[right], s_list[left]
                # Move pointers inward after a swap.
                left += 1
                right -= 1
                
        # Join the list back into a string.
        return "".join(s_list)

Reverse Vowels of a String in Java

class Solution {
    public String reverseVowels(String s) {
        // Convert string to char array for mutability.
        char[] chars = s.toCharArray();
        int left = 0;
        int right = chars.length - 1;
        // A string or set can be used for quick vowel lookup.
        String vowels = "aeiouAEIOU";
        
        // Use two pointers to swap vowels from the ends of the string.
        while (left < right) {
            // Find the first vowel from the left.
            while (left < right && vowels.indexOf(chars[left]) == -1) {
                left++;
            }
            
            // Find the first vowel from the right.
            while (left < right && vowels.indexOf(chars[right]) == -1) {
                right--;
            }
            
            // If pointers have not crossed, swap the vowels.
            if (left < right) {
                char temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                
                // Move pointers inward after a swap.
                left++;
                right--;
            }
        }
        
        // Convert char array back to a string.
        return new String(chars);
    }
}

Reverse Vowels of a String in C++

class Solution {
public:
    string reverseVowels(string s) {
        int left = 0;
        int right = s.length() - 1;
        
        // Helper lambda to check if a character is a vowel (case-insensitive).
        auto isVowel = [](char c) {
            c = tolower(c);
            return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
        };
        
        // Use two pointers to swap vowels from the ends of the string.
        while (left < right) {
            // Find the first vowel from the left.
            while (left < right && !isVowel(s[left])) {
                left++;
            }
            
            // Find the first vowel from the right.
            while (left < right && !isVowel(s[right])) {
                right--;
            }
            
            // If pointers have not crossed, swap the vowels.
            // C++ strings are mutable, so we can swap in-place.
            if (left < right) {
                swap(s[left], s[right]);
                // Move pointers inward after a swap.
                left++;
                right--;
            }
        }
        
        return s;
    }
};

Reverse Vowels of a String in TypeScript

function reverseVowels(s: string): string {
    // Set for O(1) vowel lookup.
    const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
    // TypeScript strings are immutable, so we work with an array of characters.
    const chars = s.split('');
    let left = 0;
    let right = chars.length - 1;

    // Use two pointers to swap vowels from the ends.
    while (left < right) {
        // Find the first vowel from the left.
        while (left < right && !vowels.has(chars[left])) {
            left++;
        }

        // Find the first vowel from the right.
        while (left < right && !vowels.has(chars[right])) {
            right--;
        }

        // If pointers have not crossed, swap the vowels using destructuring assignment.
        if (left < right) {
            [chars[left], chars[right]] = [chars[right], chars[left]];
            // Move pointers inward after a swap.
            left++;
            right--;
        }
    }

    // Join the array of characters back into a string.
    return chars.join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.