Notes
All notes

Tries (LeetCode #10)

A trie (say “try”, from retrieval) is a tree that stores strings character by character. Words that begin with the same letters share a path, so a trie can answer “does any word start with app?” in time proportional to the query length — something a hash set cannot do without scanning every word. This post explains the trie from scratch, then walks five problems.

The technique

The node. Each trie node represents one character position. It has a map from a character to the child node, and a flag saying whether a word ends here.

class TrieNode:
    def __init__(self):
        self.children = {}          # char -> TrieNode
        self.is_end = False         # does a word finish at this node?

The root is empty. A word is a path of characters from the root, and is_end marks its last character. Because an inserted word and a mere prefix can end at the same node (insert "app" and "apple"), is_end is essential.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.55cm, font=\scriptsize\bfseries, inner sep=0pt},
  e/.style={n, fill=green!28}, a/.style={->, thick}]
  \node[n] (r) at (0,0) {};
  \node[n] (a) at (-1.6,-0.9) {a};
  \node[n] (b) at (0.4,-0.9) {b};
  \node[n] (ap) at (-2.1,-1.8) {p};
  \node[n] (at) at (-1.1,-1.8) {t};
  \node[e] (app) at (-2.6,-2.7) {p};
  \node[e] (apt) at (-1.6,-2.7) {t};
  \node[e] (bat) at (0.7,-1.8) {t};
  \draw[a] (r) -- node[above, font=\scriptsize] {a} (a);
  \draw[a] (r) -- node[above, font=\scriptsize] {b} (b);
  \draw[a] (a) -- (ap); \draw[a] (a) -- (at);
  \draw[a] (ap) -- (app); \draw[a] (at) -- (apt); \draw[a] (b) -- (bat);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (-1.2,-3.2) {green = a word ends here};
\end{tikzpicture}

Insert and lookup. Both walk one node per character. search also checks is_end at the end; startsWith only checks that the path exists.

class Trie:
    def __init__(self):
        self.root = TrieNode()
    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.is_end = True
    def _find(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return None
            node = node.children[ch]
        return node
    def search(self, word):
        node = self._find(word)
        return node is not None and node.is_end
    def starts_with(self, prefix):
        return self._find(prefix) is not None

The cost is \(O(L)\) in the string length, independent of how many words are stored — the trie never hashes the whole string.

Implement Trie (Prefix Tree)

The question. Implement a trie with insert(word), search(word), and startsWith(prefix). search is true only for a whole word; startsWith is true if any word begins with the prefix.

insert("apple")
search("apple")     -> True
search("app")       -> False     (no word "app" was inserted)
startsWith("app")   -> True

Walk it through. Inserting "apple" creates nodes a → p → p → l → e and marks the e node’s is_end. startsWith("app") walks a, p, p and finds a node (so true). search("app") also finds that node, but is_end is false there, so it returns False.

class Trie:
    def __init__(self):
        self.root = TrieNode()
    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.is_end = True
    def search(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                return False
            node = node.children[ch]
        return node.is_end            # must be a full word
    def starts_with(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return False
            node = node.children[ch]
        return True                    # any word with this path

Complexity. \(O(L)\) per operation, \(O(\text{total characters})\) space.

Edge cases. Empty word: search("") is true only if is_end was set on the root (i.e. an empty word was inserted). A prefix longer than any word → false.

Design Add and Search Words

The question. Support addWord(word) and search(word), where search may contain the wildcard '.' that matches any single letter.

addWord("bad"); addWord("dad"); addWord("mad")
search("pad") -> False
search(".ad") -> True
search("b..") -> True

The idea. The trie is the same. For a normal character, follow the one matching child. For a ., try every child, recursing on the rest of the word. If any branch reaches the end with is_end, the answer is true.

Walk it through for search(".ad"): at the root, . branches into b, d, m. For each, check whether "ad" continues: b → a → d with is_end — yes. So True.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.55cm, font=\scriptsize\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n] (r) at (0,0) {};
  \node[n] (b) at (-1.6,-0.9) {b}; \node[n] (d) at (0,-0.9) {d}; \node[n] (m) at (1.6,-0.9) {m};
  \node[n] (ba) at (-1.6,-1.8) {a}; \node[n, fill=green!28] (bad) at (-1.6,-2.7) {d};
  \draw[a] (r) -- (b); \draw[a] (r) -- (d); \draw[a] (r) -- (m);
  \draw[a] (b) -- (ba); \draw[a] (ba) -- (bad);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-3.2) {`.` fans out; only one branch survives};
\end{tikzpicture}
def search_wild(self, node, word):
    for i, ch in enumerate(word):
        if ch == ".":
            return any(self.search_wild(child, word[i+1:])
                       for child in node.children.values())
        if ch not in node.children:
            return False
        node = node.children[ch]
    return node.is_end

Complexity. Worst case \(O(26^L)\) for a word of all dots, but pruned by the actual children.

Edge cases. Leading, trailing, or all dots. A dot that must match a word ending.

Word Search II

The question. Given a board of letters and a list of words, return every word that can be built from adjacent cells (up/down/left/right), each cell used once.

Input:  board = [["o","a","a","n"],
                 ["e","t","a","e"],
                 ["i","h","k","r"],
                 ["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat", "oath"]

The slow way. Search the board separately for each word: the board DFS is repeated many times.

The idea. Build a trie of all the words, then DFS the board once, walking the trie in step with the grid. The moment the current path is not a trie prefix, stop — no word starts that way. So the trie prunes the entire grid search.

Walk it through. Start at every cell; from o at (0,0), the trie has an o child, go there; neighbours a (right) continues to a, then t (down) continues, then h completes "oath". Meanwhile any path that stops matching the trie (like o then e) is abandoned immediately.

def find_words(board, words):
    root = Trie()
    for w in words:
        root.insert(w)
    rows, cols, out = len(board), len(board[0]), set()
    def dfs(r, c, node, path):
        if r < 0 or r >= rows or c < 0 or c >= cols:
            return
        ch = board[r][c]
        if ch == "#" or ch not in node.children:
            return                       # not a trie prefix -> prune
        nxt = node.children[ch]
        path.append(ch)
        if nxt.is_end:
            out.add("".join(path))       # found a whole word
        board[r][c] = "#"                # mark
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            dfs(r+dr, c+dc, nxt, path)
        board[r][c] = ch                 # restore
        path.pop()
    for r in range(rows):
        for c in range(cols):
            dfs(r, c, root, [])
    return list(out)

Why it works. Every word in the list corresponds to a root-to-is_end path; the grid DFS finds exactly the paths that spell such words. The trie makes “is this still a possible word?” an \(O(1)\) step.

Complexity. \(O(R \cdot C \cdot 4^L)\) worst case, but the trie prunes far below that in practice.

Edge cases. Duplicate words are de-duplicated by the set. Words not solvable are simply never matched.

Longest Common Prefix

The question. Given a list of strings, return the longest common prefix shared by all of them, or "" if there is none.

Input:  ["flower", "flow", "flight"]
Output: "fl"

The idea. Put all words in a trie. Walk down from the root as long as there is exactly one child and no word ends — the first branch or word-end is where the common prefix stops.

Walk it through. All words begin f, then l. At l, the children are o (flower, flow) and i (flight) — two children, so the branching point is reached; the prefix is "fl".

def longest_common_prefix(words):
    trie = Trie()
    for w in words:
        trie.insert(w)
    node, prefix = trie.root, []
    while len(node.children) == 1 and not node.is_end:
        ch, node = next(iter(node.children.items()))
        prefix.append(ch)
    return "".join(prefix)

Complexity. \(O(\text{total characters})\) time. A simpler alternative sorts the words and compares the first and last, which differ as early as any pair does — but the trie is the general structure.

Edge cases. Empty list → "". A single word → the whole word (the loop stops when is_end is reached). Words with no common prefix → "".

Replace Words

The question. Given a dictionary of roots and a sentence, replace each word with the shortest root that is a prefix of it; if none, leave the word unchanged.

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

The idea. Put the roots in a trie. For each word, walk its characters down the trie; the moment you hit a node with is_end, you have found the shortest root — replace and stop. If you fall off the trie, keep the original.

Walk it through. "cattle": c → a → t reaches is_end for "cat", so replace with "cat". "rattled": r → a → t reaches is_end for "rat". "the": t is not a trie edge, so keep "the".

def replace_words(dictionary, sentence):
    trie = Trie()
    for root in dictionary:
        trie.insert(root)
    out = []
    for word in sentence.split():
        node, prefix = trie.root, []
        for ch in word:
            if ch not in node.children:
                prefix = list(word); break    # no root -> keep the word
            node = node.children[ch]
            prefix.append(ch)
            if node.is_end:                   # shortest root found
                break
        out.append("".join(prefix))
    return " ".join(out)

Complexity. \(O(\text{letters in the sentence} + \text{dictionary size})\) time.

Edge cases. A word that is itself a root → unchanged (it matches immediately). Multiple roots prefixing a word → the shortest wins because we stop at the first is_end.

Pitfalls

QQuestionSelf-check

What does a trie give you that a hash set does not, and why is lookup \(O(L)\) regardless of how many words are stored?

ASolution

A trie preserves character-level prefix structure, so it supports startsWith, autocomplete, wildcards, and ordered traversal; a hash set only answers exact membership. Lookup walks one node per character of the query, so the cost depends on the string length, not on the number of stored words.

Next: Graphs (LeetCode #11) — BFS, DFS, and topological order.