sagelearnai

Replace Words

Difficulty: Medium · Pattern: Tries · LeetCode #648

You're given a dictionary of roots and a sentence. Replace every word in the sentence that has a root as a prefix with the shortest such root. Leave words with no root unchanged.

Examples

text
dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
→ "the cat was rat by the bat"
dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
→ "a a b c"

Hints

  1. Checking every root against every word costs O(#roots × #words × len).
  2. Put the roots in a trie. For each word, walk the trie character by character and stop at the first node that ends a root.

Approach

  1. Insert every root into a trie, marking the last node with end = True.
  2. For each word, walk the trie:
    • If the next character is missing, there's no root, so keep the word.
    • If the node reached is end, replace the word with the prefix so far. Stopping at the first such node gives the shortest root.

Each word costs O(its length), so the total is linear in the input. A hash-set alternative checks every prefix word[:i] against a set of roots. It's simpler but O(L²) per word because of slicing and hashing.

Complexity

Time: O(total characters in dictionary + sentence). Space: O(total characters in dictionary).

Python solution
def replaceWords(dictionary, sentence):
    trie = {}
    for w in dictionary:
        node = trie
        for ch in w:
            node = node.setdefault(ch, {})
        node['$'] = True
    def root_of(word):
        node = trie
        for i, ch in enumerate(word):
            if ch not in node:
                return word
            node = node[ch]
            if '$' in node:
                return word[:i + 1]
        return word
    return ' '.join(root_of(w) for w in sentence.split())
JavaScript solution
function replaceWords(dictionary, sentence) {
  const trie = {};
  for (const w of dictionary) {
    let node = trie;
    for (const ch of w) node = node[ch] ??= {};
    node.$ = true;
  }
  const rootOf = (word) => {
    let node = trie;
    for (let i = 0; i < word.length; i++) {
      node = node[word[i]];
      if (!node) return word;
      if (node.$) return word.slice(0, i + 1);
    }
    return word;
  };
  return sentence.split(' ').map(rootOf).join(' ');
}