Skip to main content
Back to problems
#2785
Medium Algorithms

Sort vowels in a string

String Sorting
83.4% acceptance
Feb 25, 2026
1425
73
Given a 0-indexed string s, permute s to get a new string t such that: All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i]. The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j]. Return the resulting string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn sort_vowels(s: String) -> String {
    const VOWELS: &str = "aeiouAEIOU";
    let mut chars: Vec<char> = s.chars().collect();
    let vowel_indices: Vec<usize> = chars.iter().enumerate()
      .filter(|&(_, &c)| VOWELS.contains(c))
      .map(|(i, _)| i)
      .collect();
    let mut vowel_vals: Vec<char> = vowel_indices.iter().map(|&i| chars[i]).collect();
    vowel_vals.sort_unstable();
    for (&idx, &ch) in vowel_indices.iter().zip(vowel_vals.iter()) {
      chars[idx] = ch;
    }
    chars.iter().collect()
  }
}