Skip to main content
Back to problems
#186
Medium Algorithms

Reverse words in a string ii

Two Pointers String
56.6% acceptance
Mar 31, 2026
1118
146
Given a character array s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by a single space. Your code must solve the problem in-place, i.e. without allocating extra space.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_words(s: &mut Vec<char>) {
    let n = s.len();
    // Step 1: Reverse the entire array
    s.reverse();
    // Step 2: Reverse each word
    let mut start = 0;
    for i in 0..=n {
      if i == n || s[i] == ' ' {
        s[start..i].reverse();
        start = i + 1;
      }
    }
  }
}