sagelearnai

Implement Trie (Prefix Tree)

Difficulty: Medium · Pattern: Tries · LeetCode #208

Implement a Trie class:

  • insert(word): add a word,
  • search(word): true if the exact word was inserted before,
  • startsWith(prefix): true if any inserted word begins with prefix.

All strings are lowercase letters.

Example

text
insert("apple"); search("apple") → true; search("app") → false
startsWith("app") → true; insert("app"); search("app") → true

Hints

  1. Each node needs a map (or 26-slot array) of children and a flag marking the end of a word.
  2. search and startsWith share the same walk; they only differ in whether the final node must be marked as a word end.

Approach

Store a root node. insert walks character by character, creating missing children, and marks the last node end = True. A helper walk(s) follows s and returns the final node or None. search(w) = walk succeeded and node.end; startsWith(p) = walk succeeded. Each operation is O(L).

Complexity

Time: O(L) per operation. Space: O(total characters inserted).

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

    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True                    # end-of-word 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):
        node = self._walk(word)
        return node is not None and "$" in node

    def startsWith(self, prefix):
        return self._walk(prefix) is not None
JavaScript solution
class Trie {
  constructor() { this.root = { children: new Map(), end: false }; }
  insert(word) {
    let node = this.root;
    for (const ch of word) {
      if (!node.children.has(ch)) node.children.set(ch, { children: new Map(), end: false });
      node = node.children.get(ch);
    }
    node.end = true;
  }
  walk(s) {
    let node = this.root;
    for (const ch of s) { node = node.children.get(ch); if (!node) return null; }
    return node;
  }
  search(word) { const n = this.walk(word); return !!n && n.end; }
  startsWith(prefix) { return !!this.walk(prefix); }
}