Skip to main content
Back to problems
#1859
Easy Algorithms

Sorting the sentence

String Sorting
84.1% acceptance
Feb 25, 2026
2387
81
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn sort_sentence(s: String) -> String {
    let mut words: Vec<(usize, String)> = s.split_whitespace()
      .map(|w| {
        let idx = (w.as_bytes().last().unwrap() - b'0') as usize;
        let word = w[..w.len() - 1].to_string();
        (idx, word)
      })
      .collect();
    words.sort_unstable_by_key(|&(i, _)| i);
    words.into_iter().map(|(_, w)| w).collect::<Vec<_>>().join(" ")
  }
}