Replace Words
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Replace Words
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".\n\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Examples
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Approach 1
Level I: HashSet of Roots
Intuition
Store all roots in a HashSet. For each word in the sentence, check every possible prefix (starting from length 1) in the HashSet. Return the first match found.
⏱ O(SentenceLength * WordLength^2)💾 O(DictionaryLength * RootLength)
Detailed Dry Run
Word: 'cattle'. Check 'c', 'ca', 'cat'. 'cat' is in HashSet. Replace 'cattle' with 'cat'.
Approach 2
Level III: Trie (Optimal)
Intuition
Build a Trie from the roots. For each word in the sentence, traverse the Trie. The first
isEndOfWord node encountered provides the shortest root.⏱ O(DictionaryLength * RootLength + SentenceLength)💾 O(DictionaryLength * RootLength)
Detailed Dry Run
Trie: root -> c -> a -> t (end). Word: 'cattle'. Traverse c -> a -> t (found end). Return 'cat'.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.