Sort Vowels in a String
Put the vowels of a string in ASCII order while every other character keeps its place.
Given a string ss
Example 1
Output: "dEOpnete"
Explanation: the vowels E, e, O, e sort to E, O, e, e, and go back into the same positions.
Example 2
Output: "lYmpH"
Explanation: there are no vowels, so nothing changes.
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.
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"indexOf
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"
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
- First, keep the ten vowels in ASCII order in the constant
,ORDER , and create the array"AEIOUaeiou" with one counter per vowel.count - Loop over the characters of
. For each one,s gives its placeORDER.indexOf(c) ink . IfORDER is not -1, the character is a vowel, so add one tok .count[k] - Copy the string into the char array
, and setout to 0, the place of the smallest vowel.k - Loop over
without . Wheni is a vowel, a small inner loop movesout[i] forward past vowels whose counter is 0. Writek intoORDER.charAt(k) and lowerout[i] by one.count[k] - Return
as a new string.out
The main
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:
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 []
The order inside ORDER"aeiouAEIOU"
Complexity
The work is two passes over the string, plus a walk of k
- Time: O(n), where n is the number of characters in
. Each pass looks at every character once, and eachs call scans only the ten characters ofindexOf .ORDER only moves forward, so it takes at most ten steps in total.k - Space: O(n). The char arrays from
hold n characters each, whiletoCharArray is always ten numbers, whatever the length of the string.count
Counting sort is explained on its own in