Sort Vowels in a String

Updated on 15 July, 2025
Sort Vowels in a String header image

Problem Statement

Given a 0-indexed string s, the task is to permute it to obtain a new string t, with the following specifications:

  • Consonants in the string s should stay in their original positions.
  • Vowels should be reordered and appear in nondecreasing ASCII order.

The end goal is to rearrange s such that every vowel at position i in s (if s[i] is a vowel) is not of a higher ASCII value than a vowel at position j in t where j > i. The resulting string t after these re-adjustments should be returned.

Vowels are identified as 'a', 'e', 'i', 'o', 'u' and their uppercase variants. All other alphabets are treated as consonants. The input string s consists only of English alphabets in both uppercase and lowercase.

Examples

Example 1

Input:

s = "dEvOpsEngineeR"

Output:

"dEgOpsEnginRee"

Explanation:

The vowels are: ['E', 'O', 'E', 'i', 'e', 'e']  
After sorting by ASCII: ['E', 'E', 'O', 'e', 'e', 'i']  
They are placed back into the original positions where vowels were, while consonants remain unchanged.

Example 2

Input:

s = "ThrsDfltn"

Output:

"ThrsDfltn"

Explanation:

There are no vowels in the string, so the result remains unchanged.

Constraints

  • 1 <= s.length <= 10^5
  • s consists only of letters from the English alphabet (uppercase or lowercase).

Approach and Intuition

To solve this problem, follow these steps:

  1. Identify and Extract Vowels: Traverse the string and collect all vowels in a list. Also, record the positions of vowels in the original string.

  2. Sort the Vowels: Use the built-in sort() function to sort the extracted vowels based on ASCII order. This ensures that uppercase vowels (e.g., 'A') come before lowercase ones (e.g., 'a'), matching the ASCII ordering constraint.

  3. Rebuild the String: Traverse the original string again. For each index:

    • If the character at the index is a consonant, copy it as-is.
    • If it's a vowel, replace it with the next vowel from the sorted list.

This approach ensures:

  • Time complexity: O(n log n) — due to sorting the vowels.
  • Space complexity: O(n) — to store the vowel list and build the final result.

By decoupling the vowel sorting from the consonant positions, this solution provides both correctness and clarity.

Solutions

  • C++
cpp
class Solution {
public:
    // Check if it is a vowel
    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 reorderVowels(string inputStr) {
        unordered_map<char, int> frequency;
    
        for (char x : inputStr) {
            if (checkVowel(x)) {
                frequency[x]++;
            }
        }
    
        string vowelOrder = "AEIOUaeiou";
        string resultString;
        int index = 0;
        for (int idx = 0; idx < inputStr.size(); idx++) {
            if (!checkVowel(inputStr[idx])) {
                resultString += inputStr[idx];
            } else {
                while (frequency[vowelOrder[index]] == 0) {
                    index++;
                }
                resultString += vowelOrder[index];
                frequency[vowelOrder[index]]--;
            }
        }
        return resultString;
    }
};

The provided C++ solution involves sorting the vowels in a string while keeping consonants in their original positions. The solution defines a class Solution with two main functions: checkVowel and reorderVowels.

  • The checkVowel function checks if a character is a vowel (both uppercase and lowercase are considered). It returns true if the character is a vowel; otherwise, it returns false.

  • The reorderVowels function performs the main task of reordering the vowels. Follow these steps for clarity:

    1. Create an unordered_map named frequency to store the frequency of each vowel in the input string.

    2. Iterate over each character in the input string. Use the checkVowel function to filter the vowels and update their count in the frequency map.

    3. Prepare a string vowelOrder containing all vowels in the desired order (uppercase followed by lowercase).

    4. Initiate an empty string resultString to construct the output and an index variable set to zero.

    5. Iterate over the input string again. For each character:

      • If the character is not a vowel, append it directly to resultString.
      • If it is a vowel, find the next vowel in vowelOrder that has a non-zero frequency using the index variable. Append this vowel to resultString and decrement its count in the frequency map.
    6. Return resultString which now contains the original consonants in their positions and vowels sorted in the specified order.

The implementation effectively reorders vowels while maintaining the position of consonants, adhering to a predefined vowel ordering sequence. This approach assumes valid input strings and does not handle special characters or numbers - focusing only on alphabetical characters.

  • Java
java
class Solution {
    boolean checkVowel(char character) {
        return "aeiouAEIOU".indexOf(character) != -1;
    }
    
    public String reorderVowels(String str) {
        int[] freq = new int[256];
    
        for (char ch : str.toCharArray()) {
            if (checkVowel(ch)) {
                freq[ch]++;
            }
        }
    
        String vowelOrder = "AEIOUaeiou";
        StringBuilder result = new StringBuilder();
        int index = 0;
    
        for (int i = 0; i < str.length(); i++) {
            if (!checkVowel(str.charAt(i))) {
                result.append(str.charAt(i));
            } else {
                while (freq[vowelOrder.charAt(index)] == 0) {
                    index++;
                }
    
                result.append(vowelOrder.charAt(index));
                freq[vowelOrder.charAt(index)]--;
            }
        }
        return result.toString();
    }
};

This Java solution presents a method to sort the vowels in a given string while keeping the consonants in their original order. Here's how the code solves the problem:

  • Define a helper method checkVowel that determines if a character is a vowel by checking its presence in the string "aeiouAEIOU".
  • In the main method reorderVowels, initialize a frequency array freq to store the frequency of each vowel encountered.
  • Iterate over each character in the input string. Update the frequency array for vowels using their ASCII values as indexes.
  • Maintain a predetermined order of vowels 'AEIOUaeiou' to have a structured sorting manner with uppercase vowels preceding the lowercase.
  • Use a StringBuilder to construct the output string. Walk through each character in the original string:
    • If it's not a vowel, append it directly to the result.
    • If it is a vowel, find the next vowel in the vowelOrder that has a non-zero frequency, append it, and decrement the frequency.
  • Lastly, convert the StringBuilder to a string and return it.

Thus, the provided method reorders all vowels in the input string according to a defined sequence while ensuring consonants remain as they are in the original string.

Comments

No comments yet.