Skip to main content
Back to problems
#345
Easy Algorithms

Reverse vowels of a string

Two Pointers String
60.7% acceptance
Jan 12, 2026
5325
2858
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_vowels(s: String) -> String {
    let mut chars: Vec<char> = s.chars().collect();
    let mut left = 0;
    let mut right = chars.len() - 1;
    
    let is_vowel = |c: char| -> bool {
      matches!(c, 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U')
    };
    
    while left < right {
      while left < right && !is_vowel(chars[left]) {
        left += 1;
      }
      while left < right && !is_vowel(chars[right]) {
        right -= 1;
      }
      if left < right {
        chars.swap(left, right);
        left += 1;
        right -= 1;
      }
    }
    
    chars.into_iter().collect()
  }
}