SDE & MLE Prep

208. Implement Trie (Prefix Tree)

Problem

Implement a Trie (prefix tree) with insert(word), search(word) (was this exact word inserted?) and startsWith(prefix) (was any word with this prefix inserted?).

Example: insert("apple") → search("apple") = true, search("app") = false, startsWith("app") = true

Constraints: lowercase letters; up to 3·10⁴ calls.

Walk/create child nodes char by char. search needs end at the last node; startsWith only needs the path to exist.

Complexity: O(L) per operation.

class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True                 # end marker

    def _walk(self, s):
        node = self.root
        for ch in s:
            if ch not in node:
                return None
            node = node[ch]
        return node

    def search(self, word: str) -> bool:
        node = self._walk(word)
        return node is not None and "$" in node

    def startsWith(self, prefix: str) -> bool:
        return self._walk(prefix) is not None