LeetCode Entry

2785. Sort Vowels in a String

11.09.2025 medium 2025 kotlin rust

Sort vowels

2785. Sort Vowels in a String medium blog post substack youtube

1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1109

Problem TLDR

Sort vowels #medium

Intuition

Just implementation, no extra tricks.

Approach

  • copy vowels, sort, put back
  • or do a counting sort

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


// 102ms
    fun sortVowels(s: String) = buildString {
        val vw = s.filter { it in "aeiouAEIOU" }.toList().sorted()
        var i = 0
        for (c in s) append(if (c in "aeiouAEIOU") vw[i++] else c)
    }


// 27ms
    fun sortVowels(s: String) = buildString {
        val v = "AEIOUaeiou"; val vw = IntArray(12)
        for (c in s) ++vw[1 + v.indexOf(c)]
        for (c in s) append(if (c in v)
            v[(0..10).first {vw[it+1] > 0}.also {--vw[it+1]}] else c)
    }


// 10ms
    pub fn sort_vowels(s: String) -> String {
        let mut t = s.chars().filter(|&c| "AEIOUaeiou".contains(c)).sorted();
        s.chars().map(|c| if "AEIOUaeiou".contains(c) { t.next().unwrap() } else { c }).collect()
    }