Replace Words
Replace Words is LeetCode 648 (Medium). You get a dictionary of short words called roots and a sentence of words separated by single spaces. Return the sentence with every word replaced by a root it starts with:
- Root found: if the word begins with a root, replace the whole word with that root (
cattlebecomescat). - Several roots fit: use the shortest one.
- No root fits: keep the word unchanged.
There can be 1000 roots and 1000 words, so comparing every word with every root repeats a lot of work.
- 1 <= dictionary.length <= 1000
- 1 <= dictionary[i].length <= 100
- dictionary[i] consists of only lower-case letters.
- 1 <= sentence.length <= 10⁶
- sentence consists of only lower-case letters and spaces.
- The number of words in sentence is in the range [1, 1000]
- The length of each word in sentence is in the range [1, 1000]
- Every two consecutive words in sentence will be separated by exactly one space.
- sentence does not have leading or trailing spaces.
Intuition
For each word we need the shortest root that is a prefix of it. A trie of the roots answers that with one walk down the tree per word.
Store every root in the trie and mark the node where each root ends. Then read a word one letter at a time from the top. The walk meets the word's prefixes in order of length, one letter, then two, then three, so the first marked node it reaches is the shortest root that fits. If a letter has no branch, no root can start the word, and the word stays as it is.
Use a trie when many strings must be checked against one fixed set of prefixes, and you want the shortest (or longest) prefix that fits. One walk per string replaces a comparison against every entry in the set.
Approach
Before reading on, find the root for rattled with roots cat, bat, rat, and say how you would do it without trying every root. Aim for O(D + S) time, where D and S are the letters in the dictionary and the sentence.
Build the trie
For each root, walk down from the top node, create a child for any letter that is missing, and mark the node where the root ends. Roots that begin the same way, like cat and car, share those nodes, so building costs one step per root letter.
Walk each word down the trie
Start at the top node and read the word one letter at a time. Each letter leads to one of three cases:
- No child for the letter: no root starts this way, so keep the whole word.
- The child is marked: the letters read so far form a root, and the first root met is the shortest, so return it at once.
- Otherwise: move down to the child and read the next letter.
If the word runs out before any mark, keep the whole word as well.
Rebuild the sentence
Split the sentence into words, replace each word on its own, and join the results with single spaces in the original order.
Code in Python, C++ and Java
b, so it gets a new branch from the top. Its last node is marked as the end of a root.r, so it gets a new branch from the top. Its last node is marked as the end of a root.t, so no root can be a prefix of the. The walk stops and the word is kept unchanged.cattle at the top node. The trie has a child for c, so move down to it. The node is not marked, so c is not a root yet: read the next letter.a, so move down to it. The node is not marked, so ca is not a root yet: read the next letter.t lands on a marked node, so cat is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace cattle with it and stop.w, so no root can be a prefix of was. The walk stops and the word is kept unchanged.rattled at the top node. The trie has a child for r, so move down to it. The node is not marked, so r is not a root yet: read the next letter.a, so move down to it. The node is not marked, so ra is not a root yet: read the next letter.t lands on a marked node, so rat is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace rattled with it and stop.by at the top node. The trie has a child for b, so move down to it. The node is not marked, so b is not a root yet: read the next letter.b no root continues with y, so no root can be a prefix of by. The walk stops and the word is kept unchanged.t, so no root can be a prefix of the. The walk stops and the word is kept unchanged.battery at the top node. The trie has a child for b, so move down to it. The node is not marked, so b is not a root yet: read the next letter.a, so move down to it. The node is not marked, so ba is not a root yet: read the next letter.t lands on a marked node, so bat is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace battery with it and stop.the cat was rat by the bat.b, so it gets a new branch from the top. Its last node is marked as the end of a root.c, so it gets a new branch from the top. Its last node is marked as the end of a root.a lands on a marked node, so a is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace aadsfasf with it and stop.a lands on a marked node, so a is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace absbs with it and stop.b lands on a marked node, so b is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace bbab with it and stop.c lands on a marked node, so c is a root. It is the first mark on the walk, and the walk meets shorter prefixes first, so it is the shortest root. Replace cadsfafs with it and stop.a a b c.Common pitfalls
Walking past the first root
if "$" in node:
found = word[: i + 1] # keeps walkingif "$" in node:
return word[: i + 1]With roots a and ab, the word abc passes the end of a first. If the loop keeps going, it overwrites the answer with the longer root ab.
Following a branch that does not exist
for ch in word:
node = node[ch]for ch in word:
if ch not in node:
return word
node = node[ch]Most words have no root, so the walk often reaches a letter with no child. Without the check Python raises KeyError and C++ follows a null pointer.
Complexity
Replace Words FAQ
Can it be solved with a hash set instead of a trie?
Yes. Put the roots in a set, then for each word test word[:1], word[:2], and so on, and return the first prefix that is in the set. It is shorter to write, but each test builds a new substring, so a word of length L costs O(L²) instead of O(L). With roots of at most 100 letters you can stop testing after 100 prefixes, and it still passes.
Does the order of roots in the dictionary matter?
Not for the trie: the walk finds the shortest root whatever order the roots were inserted in. It does matter for a loop like for root in dictionary: if word.startswith(root): return root, which returns the first root in the list, not the shortest. That loop needs the dictionary sorted by length first.
How is the trie written in Python?
As nested dictionaries: each node is a dict from a letter to the child node, and the key "$" marks the end of a root. node.setdefault(ch, {}) creates a child only when it is missing, so inserting a root is a three-line loop.