Skip to content

Replace Words

Replace every word in a sentence with the shortest dictionary root that starts it, using a trie.

MediumTries
Solve on LeetCode

The problem

You get a list of roots dictionary and a sentence of lowercase words separated by single spaces. Replace each word that starts with some root by the shortest such root, and leave every other word as it is. Return the new sentence.

Input dictionary = ["sun", "rain", "su"], sentence = "sunny rainbow sunday sky"

Output "su rain su sky"

sunny starts with both su and sun, and the shorter su wins. No root starts sky.

Input dictionary = ["tea", "teapot"], sentence = "teapot tea team"

Output "tea tea tea"

tea is a root of all three words, including tea itself.

Key constraint: The sentence can be a million characters long, so testing every root against every word is too slow.

How to spot the pattern

  • You match many words against a set of prefixes.
  • You want the shortest matching prefix, which is the first one you meet walking down a trie.

The idea

Put all the roots in a trie and mark the node where each root ends. For a word, walk down the trie letter by letter: the first marked node you reach is the shortest root that starts the word, so you can stop right there. If the walk breaks off, or the word ends first, no root fits and the word stays as it is.

Brute force: Test every root against every word with a prefix check, which costs O(words * roots * root length).

Step by step

  1. 1Insert every root into a trie and mark the node where it ends.
  2. 2Split the sentence on spaces.
  3. 3For each word, walk the trie letter by letter from the top.
  4. 4If a letter is missing, keep the word; if you reach a marked node after i + 1 letters, replace the word with its first i + 1 letters.
  5. 5Join the results with single spaces.

Code

class TrieNode:
    def __init__(self):
        self.children = {}  # letter -> TrieNode
        self.is_root = False  # True when a dictionary root ends at this node


class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        trie = TrieNode()
        for root in dictionary:
            node = trie
            for ch in root:
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
            node.is_root = True

        def shortest_root(word: str) -> str:
            node = trie
            for i, ch in enumerate(word):
                node = node.children.get(ch)
                if node is None:
                    return word  # no root is a prefix of this word
                if node.is_root:
                    return word[: i + 1]  # the first root you meet is the shortest
            return word

        return " ".join(shortest_root(word) for word in sentence.split(" "))

Complexity

Time

O(D + S)

Space

O(D + S)

D is the total length of the roots and S the length of the sentence. Building the trie touches each root letter once, each word walk stops at its shortest root or its last letter, and the new sentence is at most S long.

Watch out for

  • Taking the longest matching root instead of the shortest one.
  • Using a root that is longer than the word, like sunshine for sun: a root has to be a prefix of the word.

Follow-up questions

Can you do it without a trie?

Put the roots in a hash set and test each word's prefixes from shortest to longest. Building those prefixes costs O(L^2) per word, which is fine when words are short.

What if many sentences use the same dictionary?

Build the trie once and reuse it, so each sentence costs only its own length.

In Hinglish

Saare roots ko trie mein daalo. Har word ke letters ke saath trie mein neeche jao; jo pehla root khatam hota mile, wahi sabse chhota root hai, wahin ruk jao.

Related problems