LeetCode #648 Medium

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 (cattle becomes cat).
  • 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.

Constraints
  • 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.
triestringshash-table
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def replaceWords(self, dictionary: List[str], sentence: str) -> str:
▶3 trie = {}
▶4 for root in dictionary:
▶5 node = trie
▶6 for ch in root:
▶7 node = node.setdefault(ch, {})
▶8 node["$"] = True
▶9 
▶10 def shortest_root(word):
▶11 node = trie
▶12 for i, ch in enumerate(word):
▶13 if ch not in node:
▶14 return word
▶15 node = node[ch]
▶16 if "$" in node:
▶17 return word[: i + 1]
▶18 return word
▶19 
▶20 return " ".join(shortest_root(w) for w in sentence.split())
trieend of a roottacansweremptyinsert root cat
rootcat
roots inserted1 / 3
Build the trie. Each root becomes a path from the top node, one letter per node, and the node where it ends is marked green. Later each word only has to walk down this tree once.
trieend of a roottactabansweremptyinsert root bat
rootbat
roots inserted2 / 3
Insert bat. No root so far starts with b, so it gets a new branch from the top. Its last node is marked as the end of a root.
trieend of a roottactabtaransweremptyinsert root rat
rootrat
roots inserted3 / 3
Insert rat. No root so far starts with r, so it gets a new branch from the top. Its last node is marked as the end of a root.
trieend of a roottactabtarwordtheanswertheno branch for t: keep the
wordthe
lettert
answerthekept as it is
No root starts with t, so no root can be a prefix of the. The walk stops and the word is kept unchanged.
trieend of a roottactabtarwordcattleanswerthefollow c: no root ends here yet
wordcattle
letters readc
Start 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.
trieend of a roottactabtarwordcattleanswerthefollow a: no root ends here yet
wordcattle
letters readca
The trie has a child for a, so move down to it. The node is not marked, so ca is not a root yet: read the next letter.
trieend of a roottactabtarwordcattleanswerthecatcat is a root: cattle → cat
wordcattle
letters readcat
answercatshortest root
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.
trieend of a roottactabtarwordwasanswerthecatwasno branch for w: keep was
wordwas
letterw
answerwaskept as it is
No root starts with w, so no root can be a prefix of was. The walk stops and the word is kept unchanged.
trieend of a roottactabtarwordrattledanswerthecatwasfollow r: no root ends here yet
wordrattled
letters readr
Start 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.
trieend of a roottactabtarwordrattledanswerthecatwasfollow a: no root ends here yet
wordrattled
letters readra
The trie has a child for a, so move down to it. The node is not marked, so ra is not a root yet: read the next letter.
trieend of a roottactabtarwordrattledanswerthecatwasratrat is a root: rattled → rat
wordrattled
letters readrat
answerratshortest root
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.
trieend of a roottactabtarwordbyanswerthecatwasratfollow b: no root ends here yet
wordby
letters readb
Start 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.
trieend of a roottactabtarwordbyanswerthecatwasratbyno branch for y: keep by
wordby
lettery
answerbykept as it is
After b no root continues with y, so no root can be a prefix of by. The walk stops and the word is kept unchanged.
trieend of a roottactabtarwordtheanswerthecatwasratbytheno branch for t: keep the
wordthe
lettert
answerthekept as it is
No root starts with t, so no root can be a prefix of the. The walk stops and the word is kept unchanged.
trieend of a roottactabtarwordbatteryanswerthecatwasratbythefollow b: no root ends here yet
wordbattery
letters readb
Start 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.
trieend of a roottactabtarwordbatteryanswerthecatwasratbythefollow a: no root ends here yet
wordbattery
letters readba
The trie has a child for a, so move down to it. The node is not marked, so ba is not a root yet: read the next letter.
trieend of a roottactabtarwordbatteryanswerthecatwasratbythebatbat is a root: battery → bat
wordbattery
letters readbat
answerbatshortest root
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.
trieend of a roottactabtaranswerthecatwasratbythebatjoin with single spaces
answerthe cat was rat by the bat
Done. Every word walked the trie once and stopped at its first marked node or at a missing branch. Joining the words with single spaces gives the cat was rat by the bat.
05

Common pitfalls

Walking past the first root

✗ Wrong
if "$" in node:
    found = word[: i + 1]  # keeps walking
✓ Right
if "$" 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

✗ Wrong
for ch in word:
    node = node[ch]
✓ Right
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.

06

Complexity

Time
O(D + S)
Space
O(D)
Here D is the number of letters in the dictionary and S the number in the sentence. Building the trie touches each root letter once, and each word walks at most its own length. The trie holds at most D nodes.
07

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.