DSA Trie

Replace Words

Replace every word in a sentence with the shortest dictionary root that prefixes it.

Medium
Time O(D + S) Space O(D)
LeetCode
5 min read
trie strings

Problem#

Given a dictionary of roots and a sentence, replace each word with its shortest matching root (any prefix of the word that exists in the dictionary). If no root matches, keep the word.

Examples#

  • 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".

Constraints#

  • 1 <= dictionary.length <= 1000, 1 <= sentence.length <= 10^6.

Hints#

Hint
Insert roots into a trie. For each word, walk the trie until you reach an isEnd node — that’s the shortest matching root.

Approach#

Build a trie from dictionary roots. For each sentence word, walk the trie character by character; stop and emit the prefix on the first isEnd node. If you exhaust the word without hitting isEnd, keep the original.

Solution#

Replace Words
class Solution {
struct Node {
Node* child[26]{};
bool isEnd = false;
};
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Node* root = new Node();
for (auto& w : dictionary) {
Node* cur = root;
for (char c : w) {
int i = c - 'a';
if (!cur->child[i]) cur->child[i] = new Node();
cur = cur->child[i];
}
cur->isEnd = true;
}
string ans, word;
sentence.push_back(' ');
for (char c : sentence) {
if (c == ' ') {
Node* cur = root;
int matched = 0;
for (int i = 0; i < (int)word.size(); ++i) {
int idx = word[i] - 'a';
if (!cur->child[idx]) break;
cur = cur->child[idx];
++matched;
if (cur->isEnd) break;
}
if (cur && cur->isEnd) ans.append(word, 0, matched);
else ans.append(word);
ans.push_back(' ');
word.clear();
} else {
word.push_back(c);
}
}
if (!ans.empty()) ans.pop_back(); // trim trailing space
return ans;
}
};

Editorial#

Tries make “shortest prefix match” trivially O(L) per word — you can stop the walk the instant you see isEnd, which is the shortest root by construction (insertion order doesn’t matter — the trie depth picks the shorter). The token loop scans the sentence in O(S).

Complexity#

  • Time: O(D + S).
  • Space: O(D) for the trie.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.