Sort Vowels by Frequency Problem
Description
LeetCode Problem 3913.
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 <= 10^5sconsists of lowercase English letters
Solution
Approach: Counting + Stable Sort
Count how often each vowel occurs, and list the vowels that appear in s in the order of their first occurrence.
Sort this list by frequency in non-increasing order with a stable sort, so vowels with equal frequency keep their first-occurrence order.
Then walk through s. At every vowel position write the current vowel from the sorted list, and decrease its remaining count. When the count reaches 0, move to the next vowel in the list. Consonants stay where they are.
Complexity: time O(n + k log k) and space O(n), where n is the length of s and k <= 5 is the number of distinct vowels.
class Solution:
def sortVowels(self, s: str) -> str:
st = set("aeiou")
vowels = []
cnt = Counter()
for c in s:
if c not in st:
continue
if c not in cnt:
vowels.append(c)
cnt[c] += 1
vowels.sort(key=lambda c: -cnt[c])
ans = list(s)
i = 0
for k, c in enumerate(s):
if c not in st:
continue
ans[k] = c = vowels[i]
cnt[c] -= 1
if cnt[c] == 0:
i += 1
return "".join(ans)