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.
Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"
Example 2:
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" Output: "a a b c"
Constraints:
1 <= dictionary.length <= 10001 <= dictionary[i].length <= 100dictionary[i] consists of only lower-case letters.1 <= sentence.length <= 106sentence consists of only lower-case letters and spaces.sentence is in the range [1, 1000]sentence is in the range [1, 1000]sentence will be separated by exactly one space.sentence does not have leading or trailing spaces.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for replacing words involves checking every possible prefix of each word in a sentence against a dictionary of root words. For each word, we try all prefixes to see if they exist in the dictionary. If a shorter prefix matches, we replace the original word with that prefix.
Here's how the algorithm would work step-by-step:
def replace_words_brute_force(dictionary, sentence):
words = sentence.split()
replaced_words = []
for word in words:
shortest_root = None
for prefix_length in range(1, len(word) + 1):
prefix = word[:prefix_length]
# Check if the prefix is a root in the dictionary
if prefix in dictionary:
shortest_root = prefix
break
# If a root was found, use it; otherwise, keep the original word
if shortest_root:
replaced_words.append(shortest_root)
else:
replaced_words.append(word)
# Join the replaced words back into a sentence
return ' '.join(replaced_words)The fastest way to solve this problem is to use a special kind of data structure to quickly check if a word starts with one of the root words. We build this data structure from the list of root words, and then use it to process the sentence.
Here's how the algorithm would work step-by-step:
class TrieNode:
def __init__(self):
self.children = {}
self.is_root = False
class WordReplacement:
def __init__(self):
self.trie_root = TrieNode()
def build_trie(self, dictionary):
for root_word in dictionary:
current_node = self.trie_root
for char in root_word:
if char not in current_node.children:
current_node.children[char] = TrieNode()
current_node = current_node.children[char]
current_node.is_root = True
def find_replacement(self, word):
current_node = self.trie_root
replacement_word = ""
for char in word:
if char in current_node.children:
replacement_word += char
current_node = current_node.children[char]
if current_node.is_root:
return replacement_word
else:
return word
return word
def replaceWords(self, dictionary, sentence):
# Build the trie using the root words
self.build_trie(dictionary)
words = sentence.split()
replaced_words = []
for word in words:
# Find the shortest root word that prefixes the current word
replacement = self.find_replacement(word)
replaced_words.append(replacement)
# Join the words back into a sentence
return " ".join(replaced_words)
def replace_words(dictionary, sentence):
word_replacer = WordReplacement()
return word_replacer.replaceWords(dictionary, sentence)| Case | How to Handle |
|---|---|
| Empty dictionary | Return the original sentence unchanged since no replacements are possible. |
| Empty sentence | Return an empty string since there are no words to process. |
| Null dictionary or sentence | Throw an IllegalArgumentException or return null after checking for null inputs. |
| Dictionary contains an empty string | The empty string will match any word in the sentence, so return a string where all words are replaced with the empty string. |
| Sentence contains words with no prefixes in the dictionary | These words should remain unchanged in the resulting sentence. |
| Dictionary contains prefixes that are also words (e.g., 'a' and 'apple') | The solution should still select the shortest prefix ('a' in this case). |
| Sentence contains leading/trailing/multiple spaces | Trim the sentence and handle multiple spaces between words correctly to avoid empty words. |
| Large dictionary and sentence | Consider using a Trie data structure for the dictionary to achieve efficient prefix matching. |