Chapter 15 · Trees

Tries

A trie (from retrieval) stores strings character by character. Each path from root to a terminal node spells out a word. The power: all words with a common prefix share their prefix nodes. Lookup is O(L) where L is the key length — independent of how many keys are stored.

What is a trie?

A trie (prefix tree) stores strings character by character along paths from the root, so words that share a prefix share nodes. Looking up a word or checking a prefix takes O(length of the word), whatever the number of stored words. That makes tries ideal for autocomplete, spell-checkers and IP routing tables.

class Trie {
  root = {};
  insert(word) {
    let node = this.root;
    for (const ch of word) node = node[ch] ??= {};
    node.end = true;
  }
  startsWith(prefix) {
    let node = this.root;
    for (const ch of prefix) if (!(node = node[ch])) return false;
    return true;
  }
}

Structure: inserting “cat”, “car”, “card”, “care”

·cat✓r✓d✓e✓

"cat", "car", "card", "care" — all share the prefix "ca"

“cat” and “car/card/care” share the prefix “ca” — only 2 nodes for those 2 characters regardless of how many words start with “ca”. Nodes marked ✓ are terminal (end of a word).

Live demo — tree structure explorer

A trie is a tree where each edge represents a character. Build a BST below to practise tree thinking — the node-and-pointer structure is the same mental model used in tries.

Binary Search Tree
preset:
normalpathfounddelete

Tree is empty — insert a value or click a preset above

→ Insert values to build your BST

Node structure & operations

trie.pseudo
1TrieNode:
2 children <- Map[char -> TrieNode] // up to 26 for lowercase alpha
3 isEndOfWord <- false
4 
5insert(root, word):
6 node <- root
7 for each char c in word:
8 if c not in node.children:
9 node.children[c] <- new TrieNode()
10 node <- node.children[c]
11 node.isEndOfWord <- true // mark terminal
12 
13search(root, word) -> bool:
14 node <- root
15 for each char c in word:
16 if c not in node.children: return false
17 node <- node.children[c]
18 return node.isEndOfWord // must be terminal, not just prefix
19 
20startsWith(root, prefix) -> bool:
21 node <- root
22 for each char c in prefix:
23 if c not in node.children: return false
24 node <- node.children[c]
25 return true // prefix exists (may not be full word)

Autocomplete: collect all words with prefix

trie-autocomplete.pseudo
1autocomplete(root, prefix) -> list of words:
2 node <- root
3 for each char c in prefix: // navigate to prefix end
4 if c not in node.children: return []
5 node <- node.children[c]
6 results <- []
7 dfs(node, prefix, results) // collect all words from here
8 return results
9 
10dfs(node, current, results):
11 if node.isEndOfWord: results.append(current)
12 for each (char c, child) in node.children:
13 dfs(child, current + c, results)

Trie vs Hash Map for string keys

Trie

  • + Prefix queries in O(L)
  • + Alphabetical iteration naturally
  • + No hash collisions
  • − High memory (many children pointers per node)
  • − Poor cache locality

Hash Map

  • + O(L) average insert/lookup
  • + Compact storage
  • + Good cache locality
  • − No prefix queries
  • − Collision handling complexity

Real-world uses

Search autocomplete (Google, IDE intellisense)
Spell checkers and suggestions
IP routing tables (longest prefix match)
Phone number lookup (T9 predictive text)
DNA sequence matching
Boggle / word game solving

Time & space complexity

insert, search, startsWith — L = length of key, independent of nO(L)

O(L) time

space — total characters across all n inserted words (shared prefixes amortize)O(n)

Linear time

autocomplete — proportional to words matching the prefixO(n)

Linear time

🎯 Quick Check

A trie contains 'apple', 'app', 'application'. How many nodes does the root-to-leaf path for 'application' share with 'apple'?

🧠Compressed tries (Radix trees)
A standard trie wastes nodes on long single-child chains. A compressed trie (radix tree / Patricia tree) collapses chains of single-child nodes into one edge labeled with a substring. This is how IP routing tables work — they store millions of prefixes with minimal memory using compressed tries.

Tries: summary

Key points

  • Each node marks whether a complete word ends there.
  • Autocomplete: walk to the prefix's node, then collect all words below it.
  • Tries can use a lot of memory; compressed tries (radix trees) merge single-child chains.

Frequently asked questions

›Trie vs hash set for words?

A hash set checks whole words in O(1) average but can't answer prefix queries efficiently. A trie answers prefix and autocomplete queries in O(prefix length).