13.11.2023
2785. Sort Vowels in a String medium
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/402
Problem TLDR
Sort vowels in a string
Intuition
The sorted result will only depend of the vowels frequencies.
Approach
Let’s use Kotlin API:
groupBy
mapValues
buildString
Complexity
Time complexity:
O(n)Space complexity:
O(n)
Code
fun sortVowels(s: String): String {
val freq = s.groupBy { it }.mapValues({ it.value.size }).toMutableMap()
val vl = mutableListOf('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u')
val vs = vl.toSet()
return buildString {
for (c in s)
if (c in vs) {
while (freq[vl.first()].let { it == null || it <= 0 }) vl.removeFirst()
freq[vl.first()] = freq[vl.first()]!! - 1
append(vl.first())
} else append(c)
}
}