MediumNo. 0648

Replace Words — LeetCode 648 Python Solution

Pattern
Trie
Topics
Trie, Array, Hash Table, String
Reading time
6 min

The 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".

Example

Input
dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output
"the cat was rat by the bat"

Python solution

PythonSolution
class Trie:
    def __init__(self):
        self.children: List[Trie | None] = [None] * 26
        self.ref: int = -1

    def insert(self, w: str, i: int):
        node = self
        for c in w:
            idx = ord(c) - ord("a")
            if node.children[idx] is None:
                node.children[idx] = Trie()
            node = node.children[idx]
        node.ref = i

    def search(self, w: str) -> int:
        node = self
        for c in w:
            idx = ord(c) - ord("a")
            if node.children[idx] is None:
                return -1
            node = node.children[idx]
            if node.ref != -1:
                return node.ref
        return -1


class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        trie = Trie()
        for i, w in enumerate(dictionary):
            trie.insert(w, i)
        ans = []
        for w in sentence.split():
            idx = trie.search(w)
            ans.append(dictionary[idx] if idx != -1 else w)
        return " ".join(ans)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 648. Replace Words is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0692Top K Frequent WordsMedium
0720Longest Word in DictionaryMedium
0745Prefix and Suffix SearchHard

Frequently asked questions

How hard is LeetCode 648. Replace Words?

LeetCode 648. Replace Words is rated Medium on LeetCode.

What is the time complexity of LeetCode 648. Replace Words?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 648. Replace Words?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 648. Replace Words cover?

LeetCode 648. Replace Words is tagged Trie, Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.