Replace Words - Problem

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 derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".

Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.

Return the sentence after the replacement.

Input & Output

Example 1 — Basic Root Replacement
$ Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
💡 Note: "cattle" has prefix "cat", "rattled" has prefix "rat", "battery" has prefix "bat"
Example 2 — Shortest Root Priority
$ Input: dictionary = ["a","aa","aaa"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a bbab cadsfafs"
💡 Note: "aadsfasf" and "absbs" both match "a" (shortest root), other words have no matching roots
Example 3 — No Matching Roots
$ Input: dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
💡 Note: Even with "catt" in dictionary, "cat" is chosen as it's shorter and still matches "cattle"

Constraints

  • 1 ≤ dictionary.length ≤ 1000
  • 1 ≤ dictionary[i].length ≤ 100
  • 1 ≤ sentence.length ≤ 106
  • dictionary[i] and sentence consist of only lower-case letters

Visualization

Tap to expand
Replace Words: Find Shortest Root PrefixesDictionary["cat", "bat", "rat"]Sentence:"the cattle was rattled by the battery"cattlederivativecatrootbatteryderivativebatrootResult:"the cat was rat by the bat"Check prefixes
Understanding the Visualization
1
Input
Dictionary of roots and sentence with derivative words
2
Process
Find shortest root that is prefix of each word
3
Output
Sentence with derivatives replaced by roots
Key Takeaway
🎯 Key Insight: Use Trie for efficient prefix matching to find the shortest root that forms each derivative word
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
28.5K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen