Sort Vowels in a String (LeetCode 2785): Solution and Explanation
Keep every consonant of s in place and rearrange the vowels so that, read left to right, they are sorted by ASCII value. Uppercase vowels therefore come before lowercase ones.
Intuition
Consonants never move, so the positions of the vowels are fixed slots. The problem reduces to sorting the multiset of vowels and pouring it back into those slots from left to right.
A general sort would cost O(n log n), but there are only ten distinct vowels. In ASCII order they are A E I O U a e i o u: every uppercase letter (65 to 90) comes before every lowercase letter (97 to 122).
So count how many of each vowel appear, then walk the string again. At each vowel slot, take one letter from the first bucket that is not empty. A pointer k over the ten buckets only moves forward, which keeps the whole thing linear.
Approach: Counting sort over ten buckets
- Count each vowel of
sin a bucket, using the orderAEIOUaeiou. - Copy
sinto a mutable arrayoutand setk = 0. - For every index
iwhereout[i]is a vowel: advancekwhile bucketkis empty, writeorder[k]intoout[i], and decrement that bucket. - Return
outjoined into a string.
Step-by-step example
s = "lEetcOde"
- The vowels are
E(index 1),e(2),O(5) ande(6). Buckets:E:1,O:1,e:2. - Slot 1: buckets
Ais empty, so k moves toE. WriteE. - Slot 2: bucket
Eis now empty; k skipsIand lands onO. WriteO. - Slot 5:
Ois used up; k skipsUandaand reachese. Writee. Slot 6 takes the seconde. - Consonants
l,t,c,dnever moved, so the result is"lEOtcede".
Code: Python, Java, C++
1class Solution:
2 def sortVowels(self, s: str) -> str:
3 order = 'AEIOUaeiou'
4 count = {v: 0 for v in order}
5 for ch in s:
6 if ch in count:
7 count[ch] += 1
8 out = list(s)
9 k = 0
10 for i, ch in enumerate(out):
11 if ch in count:
12 while count[order[k]] == 0:
13 k += 1
14 out[i] = order[k]
15 count[order[k]] -= 1
16 return ''.join(out)1class Solution {
2 public String sortVowels(String s) {
3 String order = "AEIOUaeiou";
4 int[] count = new int[128];
5 for (char ch : s.toCharArray()) {
6 if (order.indexOf(ch) >= 0) {
7 count[ch]++;
8 }
9 }
10 char[] out = s.toCharArray();
11 int k = 0;
12 for (int i = 0; i < out.length; i++) {
13 if (order.indexOf(out[i]) >= 0) {
14 while (count[order.charAt(k)] == 0) {
15 k++;
16 }
17 out[i] = order.charAt(k);
18 count[order.charAt(k)]--;
19 }
20 }
21 return new String(out);
22 }
23}1class Solution {
2public:
3 string sortVowels(string s) {
4 const string order = "AEIOUaeiou";
5 int count[128] = {0};
6 for (char ch : s) {
7 if (order.find(ch) != string::npos) {
8 count[(int)ch]++;
9 }
10 }
11 string out = s;
12 size_t k = 0;
13 for (size_t i = 0; i < out.size(); i++) {
14 if (order.find(out[i]) != string::npos) {
15 while (count[(int)order[k]] == 0) {
16 k++;
17 }
18 out[i] = order[k];
19 count[(int)order[k]]--;
20 }
21 }
22 return out;
23 }
24};Time and space complexity
O(n)
Two passes over the string, plus at most ten moves of the bucket pointer in total.
O(n)
The output array is as long as the input. The buckets take constant space.
Other approaches
Extract, sort, write back (time O(n log n), space O(n))
Collect the vowels into a list, sort it with the built-in sort, and write them back into the vowel positions in order. It is the most direct translation of the statement.
Common mistakes
- Forgetting uppercase vowels.
A,E,I,O,Ucount as vowels too. - Sorting case-insensitively. The order is by ASCII value, so
U(85) must come beforea(97). - Treating
yas a vowel. Only a, e, i, o, u are vowels here. - Rebuilding the answer with repeated string concatenation in a loop over 100,000 characters. Write into a character array instead.
Frequently asked questions
Why does the bucket pointer never need to move backward?
Vowel slots are filled in increasing order of value. Once a bucket is empty it stays empty, so the first non-empty bucket can only be further right.
Is the counting sort really faster than calling sort?
Asymptotically yes, O(n) against O(n log n). In practice both pass easily; the counting version is the one interviewers like to see because it uses the tiny alphabet.
What is the time and space complexity?
O(n) time and O(n) space for the output string.