3913. Sort Vowels by Frequency
Description
You are given a string s consisting of lowercase English characters.
Rearrange only the vowels in the string so that they appear in non-increasing order of their frequency.
If multiple vowels have the same frequency, order them by the position of their first occurrence in s.
Return the modified string.
Vowels are 'a', 'e', 'i', 'o', and 'u'.
The frequency of a letter is the number of times it occurs in the string.
Β
Example 1:
Input: s = "leetcode"
Output: "leetcedo"
Explanation:βββββββ
- Vowels in the string are
['e', 'e', 'o', 'e']with frequencies:e = 3,o = 1. - Sorting in non-increasing order of frequency and placing them back into the vowel positions results in
"leetcedo".
Example 2:
Input: s = "aeiaaioooa"
Output: "aaaaoooiie"
Explanation:βββββββ
- Vowels in the string are
['a', 'e', 'i', 'a', 'a', 'i', 'o', 'o', 'o', 'a']with frequencies:a = 4,o = 3,i = 2,e = 1. - Sorting them in non-increasing order of frequency and placing them back into the vowel positions results in
"aaaaoooiie".
Example 3:
Input: s = "baeiou"
Output: "baeiou"
Explanation:
- Each vowel appears exactly once, so all have the same frequency.
- Thus, they retain their relative order based on first occurrence, and the string remains unchanged.
Β
Constraints:
1 <= s.length <= 105sconsists of lowercase English letters
Solutions
Solution 1: Counting + Custom Sorting
We can use a hash table \(\textit{cnt}\) to record the frequency of each vowel. We also need a list \(\textit{vowels}\) to store the vowels that appear in the string, ordered by their first occurrence.
We then sort the \(\textit{vowels}\) list with a custom comparator: vowels are sorted in non-increasing order of their frequency.
Finally, we traverse the string, replacing each vowel with the corresponding letter from the \(\textit{vowels}\) list, and update the frequency in the hash table. When the frequency of a vowel becomes 0, we move the pointer in the \(\textit{vowels}\) list forward by one.
The time complexity is \(O(n + |\Sigma| \log |\Sigma|)\) and the space complexity is \(O(n + |\Sigma|)\), where \(n\) is the length of the string and \(\Sigma\) is the set of vowels that appear in the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |