Replace Words
Problem Statement
You get a list of roots and a sentence. A word in the sentence is a derivative of a root when the word starts with that root. For example, cattle starts with the root cat.
Replace every derivative with its root. If more than one root fits a word, use the shortest one. A word with no matching root stays as it is.
Return the new sentence. Words are separated by single spaces, with no space at the start or the end.
dictionary, a list of root words, and sentence, a list of words separated by single spaces.
The sentence after the replacements.
cattle starts with cat, so it becomes cat. rattled starts with rat, and battery starts with bat. the, was and by do not start with any root, so they stay.
Each word starts with one of the roots a, b or c, so each word is cut down to that single letter.
Both roots fit cattle, so the shorter root cat wins. catalog fits only cat.
- • 1 ≤ dictionary.length ≤ 1000
- • 1 ≤ dictionary[i].length ≤ 100
- • dictionary[i] uses only lowercase letters
- • 1 ≤ sentence.length ≤ 10^6
- • sentence uses only lowercase letters and spaces
- • The sentence has between 1 and 1000 words, and each word has length 1 to 1000
- • Two neighbouring words are separated by exactly one space, with no space at the start or the end
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each word, compare with every root and keep the shortest one the word starts with
Put the roots in a hash set; for each word, look up its prefixes from shortest to longest
Insert the roots into a trie; walk each word once and stop at the first end flag
For each word in the sentence, look at every root. A root fits when the word starts with it. Among the roots that fit, keep the shortest. If no root fits, keep the word.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Trie translate into production architectures and low-level memory mechanics.