Replace Words - Problem
Replace Words is a fascinating string manipulation problem that mimics how language works with roots and derivatives.

In linguistics, a root is a base word that can be extended to form longer words called derivatives. For example, the root "help" can form the derivative "helpful" when combined with the suffix "ful".

Your Task: Given a dictionary of root words and a sentence, replace all derivatives in the sentence with their shortest possible root. If multiple roots can form the same derivative, choose the shortest root.

Example: With roots ["cat", "bat", "rat"] and sentence "the cattle was rattled by the battery", return "the cat was rat by the bat".

Input & Output

example_1.py โ€” Basic Replacement
$ Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
โ€บ Output: "the cat was rat by the bat"
๐Ÿ’ก Note: "cattle" starts with "cat", "rattled" starts with "rat", and "battery" starts with "bat". Each word is replaced with its corresponding root.
example_2.py โ€” Multiple Root Matches
$ Input: dictionary = ["a","aa","aaa"], sentence = "aadsfasf absbs bbab cadsfafs"
โ€บ Output: "a a bbab cadsfafs"
๐Ÿ’ก Note: "aadsfasf" can be replaced by "a", "aa", or "aaa", but we choose the shortest "a". "absbs" starts with "a". The other words have no matching roots.
example_3.py โ€” No Matches
$ Input: dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
โ€บ Output: "the cat was rat by the bat"
๐Ÿ’ก Note: Even though "catt" is longer than "cat", we still choose "cat" as it's the shorter root that matches "cattle". The algorithm naturally finds the shortest matching root.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(โˆ‘(len(roots)) + โˆ‘(len(words)))

Linear time to build Trie from roots, then linear time to process each character of each word once

n
2n
โœ“ Linear Growth
Space Complexity
O(โˆ‘(len(roots)))

Trie storage is proportional to total characters in all roots (with sharing for common prefixes)

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค dictionary.length โ‰ค 1000
  • 1 โ‰ค dictionary[i].length โ‰ค 100
  • dictionary[i] consists of only lower-case letters
  • 1 โ‰ค sentence.length โ‰ค 106
  • sentence consists of only lower-case letters and spaces
  • The number of words in sentence is in the range [1, 1000]
  • The length of each word in sentence is in the range [1, 1000]
  • All dictionary words are unique
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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