Skip to main content
Back to problems
#648
Medium Algorithms

Replace words

Array Hash Table String Trie
68.6% acceptance
Feb 20, 2026
3101
219
Given a dictionary of roots and a sentence, replace all derivatives with their shortest root.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
use std::collections::HashSet;
impl Solution {
  pub fn replace_words(dictionary: Vec<String>, sentence: String) -> String {
    let roots: HashSet<String> = dictionary.into_iter().collect();
    sentence
      .split_whitespace()
      .map(|word| {
        for i in 1..=word.len() {
          if roots.contains(&word[..i]) {
            return word[..i].to_string();
          }
        }
        word.to_string()
      })
      .collect::<Vec<_>>()
      .join(" ")
  }
}