Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Replace Words

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "648" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 <= 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] Every two consecutive words in sentence will be separated by exactly one space. sentence does not have leading or trailing spaces.

Explanation

Here's a breakdown of the approach, complexity, and Python code for solving this root replacement problem:

  • Trie Data Structure: Utilize a Trie (prefix tree) to efficiently store and search for the dictionary roots. This allows for quick prefix matching within the sentence words.
  • Prefix Matching: For each word in the sentence, traverse the Trie to find the shortest root that is a prefix of the word.
  • Sentence Reconstruction: Replace the derivative with the shortest root found (if any), otherwise keep the original word. Combine the words back into a sentence.

  • Runtime Complexity: O(N + M K), where N is the total number of characters in the sentence, M is the number of words in the sentence, and K is the average length of a word. Trie construction is O(L W), where L is the number of words in the dictionary, and W is the average length of a dictionary word. The search within the trie depends on the word length which is considered as K. Since dictionary size is limited, and sentence size is big, we can consider O(N + M K) Storage Complexity: O(L W), where L is the number of words in the dictionary, and W is the average length of a dictionary word. This is primarily due to storing the dictionary in the Trie.

Code

    class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_word = True

    def search_prefix(self, word):
        node = self.root
        prefix = ""
        for char in word:
            if char in node.children:
                prefix += char
                node = node.children[char]
                if node.is_word:
                    return prefix
            else:
                return None
        return prefix if node.is_word else None

def replace_words(dictionary, sentence):
    trie = Trie()
    for root in dictionary:
        trie.insert(root)

    words = sentence.split()
    result = []
    for word in words:
        prefix = trie.search_prefix(word)
        if prefix:
            result.append(prefix)
        else:
            result.append(word)

    return " ".join(result)

More from this blog

C

Chatmagic blog

2894 posts