Skip to main content
Back to problems
#3775
Medium Algorithms

Reverse words with same vowel count

Two Pointers String Simulation
66.6% acceptance
Feb 25, 2026
54
7
You are given a string s consisting of lowercase English words, each separated by a single space. Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged. Return the resulting string. Vowels are 'a', 'e', 'i', 'o', and 'u'.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_words(s: String) -> String {
    let vowels = |c: char| matches!(c, 'a'|'e'|'i'|'o'|'u'|'A'|'E'|'I'|'O'|'U');
    let count_vowels = |w: &str| w.chars().filter(|&c| vowels(c)).count();
    let words: Vec<&str> = s.split(' ').collect();
    if words.is_empty() { return s; }
    let target = count_vowels(words[0]);
    let result: Vec<String> = words.iter().enumerate().map(|(i, &w)| {
      if i > 0 && count_vowels(w) == target {
        w.chars().rev().collect()
      } else {
        w.to_string()
      }
    }).collect();
    result.join(" ")
  }
}