Replace Words (LeetCode 648): Solution and Explanation
Given a dictionary of roots and a sentence, replace every word that starts with a root by the shortest such root, and return the new sentence.
Intuition
For each word we want the shortest dictionary root that is a prefix of it. Testing every root against every word repeats the same prefix comparisons over and over.
A trie stores all roots so that shared prefixes share nodes. Walking a word down the trie checks its prefixes from shortest to longest in a single pass.
The first node on that walk that ends a root is the shortest root, so we can stop right there. If an edge is missing first, no root fits and the word stays.
Approach: Trie of roots, stop at the first end mark
- Insert every root into a trie, creating child nodes as needed, and mark the node where each root ends.
- Split the sentence into words.
- For each word, start at the trie root and follow its letters one by one.
- If the current node ends a root, stop and use that root. If the next letter has no edge, stop and keep the word.
- Join the resulting words with single spaces.
Step-by-step example
dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
- Build the trie: three branches c-a-t, b-a-t and r-a-t, each ending in a root mark.
- "the": there is no edge for 't' from the trie root, so keep "the".
- "cattle": follow c, a, t. The node after t is marked, so replace with "cat".
- "was" and "by" have no matching first letter and stay. "rattled" becomes "rat" and "battery" becomes "bat".
- Join: "the cat was rat by the bat".
Code: Python, Java, C++
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['$'] = root
9
10 out = []
11 for word in sentence.split():
12 node = trie
13 for ch in word:
14 if ch not in node or '$' in node:
15 break
16 node = node[ch]
17 out.append(node.get('$', word))
18 return ' '.join(out)1class Solution {
2 private static class TrieNode {
3 TrieNode[] next = new TrieNode[26];
4 String word;
5 }
6
7 public String replaceWords(List<String> dictionary, String sentence) {
8 TrieNode trie = new TrieNode();
9 for (String root : dictionary) {
10 TrieNode node = trie;
11 for (char ch : root.toCharArray()) {
12 if (node.next[ch - 'a'] == null) node.next[ch - 'a'] = new TrieNode();
13 node = node.next[ch - 'a'];
14 }
15 node.word = root;
16 }
17
18 StringBuilder sb = new StringBuilder();
19 for (String word : sentence.split(" ")) {
20 TrieNode node = trie;
21 for (char ch : word.toCharArray()) {
22 if (node.next[ch - 'a'] == null || node.word != null) break;
23 node = node.next[ch - 'a'];
24 }
25 if (sb.length() > 0) sb.append(' ');
26 sb.append(node.word != null ? node.word : word);
27 }
28 return sb.toString();
29 }
30}1class Solution {
2 struct TrieNode {
3 TrieNode* next[26] = {};
4 string word;
5 };
6
7public:
8 string replaceWords(vector<string>& dictionary, string sentence) {
9 TrieNode* trie = new TrieNode();
10 for (const string& root : dictionary) {
11 TrieNode* node = trie;
12 for (char ch : root) {
13 if (!node->next[ch - 'a']) node->next[ch - 'a'] = new TrieNode();
14 node = node->next[ch - 'a'];
15 }
16 node->word = root;
17 }
18
19 stringstream ss(sentence);
20 string word, out;
21 while (ss >> word) {
22 TrieNode* node = trie;
23 for (char ch : word) {
24 if (!node->next[ch - 'a'] || !node->word.empty()) break;
25 node = node->next[ch - 'a'];
26 }
27 if (!out.empty()) out += ' ';
28 out += node->word.empty() ? word : node->word;
29 }
30 return out;
31 }
32};Time and space complexity
O(D + S)
Building the trie touches each character of the roots once (D in total), and each sentence character is visited at most once during the walks (S in total).
O(D)
The trie has at most one node per root character. The output string is not counted.
Other approaches
Hash set of roots, try every prefix (time O(D + sum of w^2), space O(D))
Put the roots in a set. For each word, test prefixes of length 1, 2, 3 and so on, and stop at the first one in the set. Simple, but each prefix slice and hash costs O(length).
Compare every root with every word (time O(N * M * L), space O(1))
For each word, scan the whole dictionary with startsWith and keep the shortest match. Fine for tiny inputs only.
Common mistakes
- Continuing the walk after reaching a root mark. That would pick a longer root, but the problem asks for the shortest one.
- Forgetting the case where the word is exactly a root, or is shorter than every root that matches so far. Check the mark after the loop too.
- Building the answer with repeated string concatenation in a loop in languages where that is quadratic. Use a builder or join.
Frequently asked questions
Why does the trie give the shortest root automatically?
The walk visits prefixes in increasing length. The first marked node it meets is the shortest root that is a prefix of the word.
What if two roots are equal?
They end on the same trie node, so the node is simply marked once. The replacement is the same string either way.
Do I need to keep inserting roots that extend an existing root?
You can skip them, since the shorter root always wins, but inserting them is harmless because the walk stops at the first mark.