Sort Vowels in a String (LeetCode 2785): Solution and Explanation

Medium
String
Sorting

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

  1. Count each vowel of s in a bucket, using the order AEIOUaeiou.
  2. Copy s into a mutable array out and set k = 0.
  3. For every index i where out[i] is a vowel: advance k while bucket k is empty, write order[k] into out[i], and decrement that bucket.
  4. Return out joined into a string.

Step-by-step example

s = "lEetcOde"
  1. The vowels are E (index 1), e (2), O (5) and e (6). Buckets: E:1, O:1, e:2.
  2. Slot 1: buckets A is empty, so k moves to E. Write E.
  3. Slot 2: bucket E is now empty; k skips I and lands on O. Write O.
  4. Slot 5: O is used up; k skips U and a and reaches e. Write e. Slot 6 takes the second e.
  5. Consonants l, t, c, d never 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Counting sort over ten buckets O(n)
Extract, sort, write back O(n log n)
Time

O(n)

Two passes over the string, plus at most ten moves of the bucket pointer in total.

Space

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, U count as vowels too.
  • Sorting case-insensitively. The order is by ASCII value, so U (85) must come before a (97).
  • Treating y as 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.