algoadvance

A Trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spell checker.

Implement a Trie with the following methods:

Clarifying Questions

  1. Case Sensitivity: Should the trie treat “Apple” and “apple” as different strings?
    • Let’s assume case-sensitivity is respected (this needs to be confirmed if in a real scenario).
  2. Characters Allowed: Should we only consider lowercase English letters for simplicity?
    • Yes, for simplicity we will only consider lowercase English letters.
  3. Consecutive Inserts and Searches: Can we assume that the methods will be called multiple times and independently?
    • Yes, the methods can be called in any sequence.

Strategy

Trie Node

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: str) -> None:
        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(self, word: str) -> bool:
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return node.is_word

    def startsWith(self, prefix: str) -> bool:
        node = self.root
        for char in prefix:
            if char not in node.children:
                return False
            node = node.children[char]
        return True

Time Complexity

Here, creating/traversing nodes takes linear time with respect to the length of the word or prefix being processed.

Try our interview co-pilot at AlgoAdvance.com