Reverse Vowels of a String

Updated on 20 June, 2025
Reverse Vowels of a String header image

Problem Statement

In this task, you are given a string s. Your specific goal is to reverse the order of vowels within the string and then return the modified string. The vowels, which are 'a', 'e', 'i', 'o', and 'u' (including their uppercase versions), can occur more than once throughout the string. This operation only affects the vowels in the string, while the positions of all other characters should remain unchanged.

Examples

Example 1

Input:

s = "IceCreAm"

Output:

"AceCreIm"

Explanation:

The vowels in `s` are `['I', 'e', 'e', 'A']`. On reversing the vowels, s becomes `"AceCreIm"`.

Constraints

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

Approach and Intuition

  1. To tackle this problem, use a two-pointer approach with one pointer starting at the beginning of the string and the other at the end.
  2. Traverse the string using these two pointers, moving inwards. This way you can spot vowels from both ends effectively.
  3. When both pointers find vowels, swap them. Then, move both pointers one position: the beginning pointer to the next character and the ending pointer to the previous one.
  4. Continue this swapping process until the two pointers meet or cross each other.
  • For instance, consider a string s = "IceCreAm". The beginning pointer starts at 'I' and the ending pointer starts at 'm'.
  • Both pointers skip non-vowel characters, moving toward each other until they find vowels. They then swap these characters before moving again.
  • Final swapped result yields "AceCreIm" after swapping the vowels ['I', 'e', 'e', 'A'] to their reverse sequence.

Regarding the problem constraints:

  • The string length can be moderately large – up to 300,000 characters, which suggests that the solution needs to be efficient.
  • Since the characters are guaranteed to be printable ASCII characters, there’s no need to handle other types of characters or encodings. This simplifies the solution slightly as you do not need to worry about character encoding issues.

Solutions

  • C++
  • Java
cpp
class Solution {
public:
    bool checkVowel(char ch) {
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
               ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
    }
    
    string reverseVowels(string str) {
        int left = 0;
        int right = str.size() - 1;
        
        while (left < right) {
            while (left < str.size() && !checkVowel(str[left])) {
                left++;
            }
            
            while (right >= 0 && !checkVowel(str[right])) {
                right--;
            }
            
            if (left < right) {
                swap(str[left++], str[right--]);
            }
        }
        
        return str;
    }
};

This solution for reversing the vowels in a given string is implemented in C++. The Solution class contains two functions: checkVowel and reverseVowels.

  • checkVowel(char ch) determines if a character is a vowel (either lowercase or uppercase). Use a simple conditional check for each vowel.

  • reverseVowels(string str) reverses the vowels in the string. Initialize two pointers, left starting from the beginning of the string and right starting from the end.

    Use the following logic flow:

    1. Increment the left pointer until a vowel is found, or the end of the string is reached.
    2. Decrement the right pointer until a vowel is found, or the beginning of the string is reached.
    3. If left is still less than right, swap the vowels at these positions and adjust the pointers (increment left, decrement right).
    4. Repeat this process until the two pointers meet or cross.
  • Return the modified string.

This solution efficiently scans and modifies the string in place, adhering to the constraints and characteristics of the problem without using additional storage for vowel management.

java
class Solution {
    // Check whether a given character is a vowel, considering upper and lower case
    boolean checkVowel(char charCheck) {
        return "aeiouAEIOU".indexOf(charCheck) != -1;
    }

    // Method to exchange characters within an array given two indices
    void exchange(char[] data, int idx1, int idx2) {
        char temporary = data[idx1];
        data[idx1] = data[idx2];
        data[idx2] = temporary;
    }
    
    public String reverseVowelsInString(String str) {
        int left = 0;
        int right = str.length() - 1;
        char[] charArray = str.toCharArray();  // Transform string to modifiable char array

        while (left < right) {
            // Advance left index until a vowel is found
            while (left < str.length() && !checkVowel(charArray[left])) {
                left++;
            }
            // Move right index back until a vowel is found
            while (right >= 0 && !checkVowel(charArray[right])) {
                right--;
            }
            // Swap vowels if appropriate indices were found
            if (left < right) {
                exchange(charArray, left++, right--);
            }
        }
        // Convert character array back to string and return
        return new String(charArray);
    }
};

The given Java code defines a solution for reversing the vowels in a string. The implementation involves defining a Solution class that provides methods to check if a character is a vowel and to exchange two characters in an array. The main logic to reverse vowels is encapsulated in the reverseVowelsInString method.

  • The checkVowel method determines if the provided character is a vowel by checking its presence in the string "aeiouAEIOU".
  • The exchange method swaps two characters in a character array, given their indices.
  • The reverseVowelsInString method first converts the string into a character array.
  • Use two pointers, left and right, initially positioned at the beginning and end of the array respectively.
  • Increment the left pointer until a vowel is found, and decrement the right pointer until a vowel is found.
  • Swap the characters at these positions if left is less than right, then adjust the pointers accordingly.
  • Continue this process until the two pointers cross each other.
  • Convert the character array back to a string and return it as the result.

This approach ensures that only vowels are reversed in their positions within the string while all other characters remain in their original positions. The use of pointers allows for efficient traversing of the string in a single pass, and direct operations on the character array ensure minimal overhead.

Comments

No comments yet.