#648

Replace Words

Medium
ArrayHash TableStringTrieTriePrefix Tree
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n * k)
💡

Intuition

Time O(n * m)Space O(n * k)

Using a Trie (prefix tree) allows us to efficiently search for roots that match the beginning of each word in the sentence. This reduces the number of comparisons needed and speeds up the process significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Build a Trie from the dictionary of roots.
  2. 2Step 2: Split the sentence into individual words.
  3. 3Step 3: For each word, traverse the Trie to find the shortest root that matches the start of the word.
  4. 4Step 4: Replace the word with the found root if it exists.
  5. 5Step 5: Join the modified words back into a sentence.
solution.py38 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_end = False
5
6class Trie:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def insert(self, word):
11        node = self.root
12        for char in word:
13            if char not in node.children:
14                node.children[char] = TrieNode()
15            node = node.children[char]
16        node.is_end = True
17
18    def search(self, word):
19        node = self.root
20        for char in word:
21            if char not in node.children:
22                return ''
23            node = node.children[char]
24            if node.is_end:
25                return word[:word.index(char)+1]
26        return ''
27
28
29def replaceWords(dictionary, sentence):
30    trie = Trie()
31    for root in dictionary:
32        trie.insert(root)
33    words = sentence.split()
34    for i in range(len(words)):
35        root = trie.search(words[i])
36        if root:
37            words[i] = root
38    return ' '.join(words)

Complexity note: The time complexity is O(n * m) where n is the number of words in the sentence and m is the average length of the words. The space complexity is O(n * k) where k is the average length of the roots stored in the Trie.

  • 1Using a Trie allows for efficient prefix searching.
  • 2Replacing words with roots improves clarity and reduces redundancy.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.