Sort Vowels in a String

Put the vowels of a string in ASCII order while every other character keeps its place.

Given a string s, return a new string in which every vowel position holds the vowels of s in sorted order. The vowels are a, e, i, o and u, in lowercase or uppercase. Every other character stays exactly where it is. Vowels are sorted by their ASCII value, the number a computer stores for each character, which puts all uppercase vowels before all lowercase ones.

Example 1
Input: s = "dEepnOte"
Output: "dEOpnete"
Explanation: the vowels E, e, O, e sort to E, O, e, e, and go back into the same positions.
Example 2
Input: s = "lYmpH"
Output: "lYmpH"
Explanation: there are no vowels, so nothing changes.
Solution

The Idea

Imagine the word "dEepnOte" written on eight tiles in a row. You may swap the vowel tiles among themselves, but the tiles d, p, n and t are glued down. The goal is to arrange the vowel tiles in sorted order, reading from left to right.

What does sorted mean for letters? Inside a computer each character is stored as a number, its ASCII value. Uppercase A to U run from 65 to 85, and lowercase a to u from 97 to 117. So E (69) and O (79) both come before e (101), even though e and E are the same letter.

Look at the picture below. In the row labelled "the string s", the orange slots 1, 2, 5 and 7 hold vowels. Taken out, they read E, e, O, e. Sorted by ASCII value, they read E, O, e, e.

The string dEepnOte has vowels in slots 1, 2, 5 and 7. Taken out they read E, e, O, e. Sorted by ASCII value they read E, O, e, e. Put back into the same slots they give dEOpnete, and the consonants d, p, n, t never move.

Where do the sorted vowels go? Back into the same orange slots, one by one from left to right. E goes into slot 1, O into slot 2, and the two e's into slots 5 and 7. The row labelled "the result" reads "dEOpnete", which is the answer.

So the slots never change; only which vowel sits in each slot does. The task comes down to sorting the vowels on their own and writing them back in order.

Solution Approach

Turning that idea into code means settling four things: how to tell a vowel from other characters, how to sort the vowels more cheaply than copying them into a list and sorting it, which order to list the ten vowels in, and how to write them back.

Spotting a vowel

How does the code know a character is a vowel? Keep the ten vowels in one string, "AEIOUaeiou", and ask for the character's place in it with indexOf. That call returns -1 for any character that is not in the string, such as d, Y or a space.

Sorting the vowels

The plain way is to copy the vowels into a list and sort it. That works, but it compares vowels again and again, about m log m times for m vowels. Is there something cheaper? Only ten different vowels can ever appear, so we can count instead of compare.

Keep ten counters, one per vowel, and add one each time that vowel shows up. For "dEepnOte" the counters say E: 1, O: 1, e: 2, and every other vowel 0. Reading the counters in ASCII order hands out E, then O, then e twice, which is the sorted list. Sorting by counting how many times each value appears is called counting sort.

Ordering the ten vowels

In which order should the ten vowels be listed? In ASCII order, so "AEIOUaeiou", uppercase first. Then a vowel's place in that string is also its rank, and reading the counters from place 0 to place 9 gives the vowels from smallest to largest.

Writing the vowels back

How do the counted vowels get back into the string? Walk along a copy of the string. At each vowel slot, take the smallest vowel that still has copies left, write it there, and lower its counter by one. Slots that hold other characters are left alone.

Java Solution

The method sortVowels works in these steps:

  1. First, keep the ten vowels in ASCII order in the constant ORDER, "AEIOUaeiou", and create the array count with one counter per vowel.
  2. Loop over the characters of s. For each one, ORDER.indexOf(c) gives its place k in ORDER. If k is not -1, the character is a vowel, so add one to count[k].
  3. Copy the string into the char array out, and set k to 0, the place of the smallest vowel.
  4. Loop over out with i. When out[i] is a vowel, a small inner loop moves k forward past vowels whose counter is 0. Write ORDER.charAt(k) into out[i] and lower count[k] by one.
  5. Return out as a new string.

The main method runs both examples, a string of reversed vowels, a mixed-case pair, two words with a space, and an empty string.

Java
public class SortVowelsInString {

    private static final String ORDER = "AEIOUaeiou";   // vowels in ASCII order

    public static String sortVowels(String s) {
        int[] count = new int[ORDER.length()];
        for (char c : s.toCharArray()) {
            int k = ORDER.indexOf(c);
            if (k >= 0) {
                count[k]++;                   // one more copy of this vowel
            }
        }
        char[] out = s.toCharArray();
        int k = 0;
        for (int i = 0; i < out.length; i++) {
            if (ORDER.indexOf(out[i]) >= 0) {
                while (count[k] == 0) {
                    k++;                      // next vowel that still has copies left
                }
                out[i] = ORDER.charAt(k);
                count[k]--;
            }
        }
        return new String(out);
    }

    public static void main(String[] args) {
        System.out.println(sortVowels("dEepnOte"));
        System.out.println(sortVowels("lYmpH"));
        System.out.println(sortVowels("uoiea"));
        System.out.println(sortVowels("aA"));
        System.out.println(sortVowels("Banana Ice"));
        System.out.println("[" + sortVowels("") + "]");
    }
}

Running it prints:

Output
dEOpnete
lYmpH
aeiou
Aa
BInana ace
[]

"dEOpnete" matches the picture, and "lYmpH" comes back unchanged because Y is not a vowel. "uoiea" turns into "aeiou", since every slot is a vowel slot. In "Aa", the uppercase A moves to the front because 65 is smaller than 97.

Look at "BInana ace". The vowels of "Banana Ice" are a, a, a, I and e, and sorted they become I, a, a, a, e. The capital I jumps to the first vowel slot, and the B, the n's, the c and the space stay put. The empty string gives []: no loop runs, so nothing breaks.

The order inside ORDER matters. Listing the vowels alphabetically as "aeiouAEIOU" puts lowercase first. With that string, a separate run turns "dEepnOte" into "deepnEtO" and leaves "aA" as "aA", both wrong.

Complexity

The work is two passes over the string, plus a walk of k through ten counters.

  • Time: O(n), where n is the number of characters in s. Each pass looks at every character once, and each indexOf call scans only the ten characters of ORDER. k only moves forward, so it takes at most ten steps in total.
  • Space: O(n). The char arrays from toCharArray hold n characters each, while count is always ten numbers, whatever the length of the string.

Counting sort is explained on its own in Counting Sort. Reverse Vowels of a String also moves only the vowels, reversing them instead of sorting them.