Skip to main content
Back to problems
#151
Medium Algorithms

Reverse words in a string

Two Pointers String
55.6% acceptance
Jan 12, 2026
10423
5565
Given an input string 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 at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_words(s: String) -> String {
    s.split_whitespace()
      .rev()
      .collect::<Vec<&str>>()
      .join(" ")
  }
}