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
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
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
โ Linear Growth
Space Complexity
O(โ(len(roots)))
Trie storage is proportional to total characters in all roots (with sharing for common prefixes)
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code