Notes
All notes

Tries (DSA #14)

A hash set answers “is this word present?” in \(O(1)\). It cannot answer “which words start with app?” without scanning every word — because hashing destroys the shared structure between words. A trie (from retrieval) keeps that structure: it stores strings character by character along a tree, so all words sharing a prefix share a path. That single property makes prefix queries, autocomplete, and dictionary-style problems fast.

This chapter covers the trie node, insert/search/startsWith, the cost model, and the problems tries solve best.

The trie node

Each node represents one character position and has:

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

The root is empty; a word is a path from the root, and is_end marks its final character.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.62cm, font=\small\bfseries, inner sep=0pt},
  e/.style={n, fill=green!28}, a/.style={->, thick}]
  \node[n] (r) at (0,0) {};
  \node[n] (a) at (-2.0,-1.0) {a};
  \node[n] (b) at (0,-1.0) {b};
  \node[n] (ap) at (-2.6,-2.0) {p};
  \node[n] (at) at (-1.2,-2.0) {t};
  \node[e] (app) at (-3.2,-3.0) {p};
  \node[e] (apt) at (-1.8,-3.0) {t};
  \node[e] (bat) at (0.3,-2.0) {t};
  \draw[a] (r) -- node[above, font=\scriptsize] {a} (a);
  \draw[a] (r) -- node[above, font=\scriptsize] {b} (b);
  \draw[a] (a) -- node[above, font=\scriptsize] {p} (ap);
  \draw[a] (a) -- node[above, font=\scriptsize] {t} (at);
  \draw[a] (ap) -- node[above, font=\scriptsize] {p} (app);
  \draw[a] (at) -- node[above, font=\scriptsize] {t} (apt);
  \draw[a] (b) -- node[above, font=\scriptsize] {a} (bat);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (-1.2,-3.5) {green = a word ends here; shared prefixes share a path};
\end{tikzpicture}

Insert, search, startsWith

All three operations walk the string one character at a time, creating or following nodes.

class Trie:
    def __init__(self):
        self.root = TrieNode()
    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        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      # exact word
    def starts_with(self, prefix):
        return self._find(prefix) is not None        # any word with prefix

The cost model is the key contrast with a hash set: a trie operation is \(O(L)\) where \(L\) is the string length, independent of how many words are stored. It never hashes the whole string, and it naturally supports prefixes.

Autocomplete: collect words under a prefix

Once you find the node for a prefix, a DFS collects every word beneath it.

def words_with_prefix(self, prefix, limit=10):
    node = self._find(prefix)
    if not node:
        return []
    out = []
    def dfs(n, path):
        if len(out) >= limit:
            return
        if n.is_end:
            out.append(prefix + "".join(path))
        for ch, child in n.children.items():
            path.append(ch); dfs(child, path); path.pop()
    dfs(node, [])
    return out

This is the core of search-box autocomplete. In production, each node often caches a few top completions or a count so the DFS can stop early, but the shape is the same.

Wildcard and dictionary problems

A trie also handles patterns that a hash map cannot, such as . matching any character (design-add-and-search-words):

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

Because the trie exposes characters one by one, wildcards, regex-like searches, and word-break segmentation (can the string be split into dictionary words?) map naturally onto it.

Where tries earn their keep

Trie vs hash map vs sorted array

Operation Hash map Sorted array Trie
Exact lookup \(O(1)\) avg \(O(\log n)\) \(O(L)\)
Prefix search \(O(n)\) \(O(\log n + k)\) \(O(L + k)\)
Ordered iteration no yes yes (DFS)
Memory compact compact can be large

The trie’s weakness is memory: each node can hold up to an alphabet-sized map. Compress chains of single-child nodes into a radix tree (Patricia trie) to save space while keeping prefix behaviour — the same idea behind IP routing tables.

Pitfalls

QQuestionSelf-check

What does a trie give you that a hash set does not? Why is trie lookup \(O(L)\) regardless of the number of stored words?

ASolution

A trie preserves character-level prefix structure, so it supports prefix queries, autocomplete, wildcards, and ordered traversal; a hash set only answers exact membership. Lookup walks one node per character of the query, so it depends on the string length \(L\), not on how many words are stored.

Next: Segment Trees (DSA #15) — range queries that survive updates.