Sort Vowels in a String

Sort the vowels in string s while keeping consonants in their original positions.

Example 1
Input: s="lEetcOde" → Output: "lEOtcede"
Example 2
Input: s="lYmpH" → Output: "lYmpH"

Solution Approach

Extract vowels, sort them, then place back at vowel positions.

  • Identify vowel positions and extract vowels
  • Sort extracted vowels
  • Place sorted vowels back at original vowel positions
  • Return reconstructed string
Java
public String sortVowels(String s) {
    String vowels = "aeiouAEIOU";
    List<Character> vowelList = new ArrayList<>();
    char[] arr = s.toCharArray();
    for (char c : arr) if (vowels.indexOf(c) >= 0) vowelList.add(c);
    Collections.sort(vowelList);
    int vi = 0;
    for (int i = 0; i < arr.length; i++)
        if (vowels.indexOf(arr[i]) >= 0) arr[i] = vowelList.get(vi++);
    return new String(arr);
}
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)