14. Trie (Prefix Tree)

The data structure behind autocomplete

You start typing "prog" into a search bar and instantly see suggestions: "program", "programming", "progress", "progressive". The system doesn't scan every word in its dictionary each time you press a key. Instead, it uses a trie -- a tree structure that organizes strings by their shared prefixes so that prefix lookups are nearly instantaneous.

The name "trie" comes from retrieval, though it's pronounced "try" to distinguish it from "tree." Invented by Edward Fredkin in 1960, the trie is one of the most elegant data structures in computer science -- and it solves a problem that hash tables fundamentally cannot.

The Problem: Fast Prefix Lookups

Suppose you need to store a dictionary of words and support these operations:

  • Insert a word
  • Search for an exact word
  • Find all words starting with a given prefix

A hash table handles the first two beautifully -- O(1) average for insert and exact lookup. But what about the third? If you want all words starting with "pre", a hash table offers no shortcut. You'd have to check every key in the entire table.

Why Hash Tables Aren't Enough

Hash functions destroy ordering. The hash of "pre" tells you nothing about where "prefix", "predict", or "prepare" ended up. There's no way to say "give me everything in the neighborhood of this key" -- every key is scattered independently.

A trie, by contrast, organizes words by their structure. Words that share a prefix share a path in the tree, so finding all words with a given prefix means finding one node and collecting its descendants.

Building a Trie

Let's build a trie by inserting these words one at a time: cat, car, card, care, do, dog.

  1. Insert "cat"

    Start at the root. Create child nodes for c, then a, then t. Mark t as a word ending.

    (root)
      └─ c
         └─ a
            └─ t*
  2. Insert "car"

    Follow the existing path c → a, then create a new child r. Mark it as a word ending.

    (root)
      └─ c
         └─ a
            ├─ t*
            └─ r*
  3. Insert "card"

    Follow c → a → r (all existing), then add d. The node for r stays marked as a word ending too.

    (root)
      └─ c
         └─ a
            ├─ t*
            └─ r*
               └─ d*
  4. Insert "care"

    Follow c → a → r, then add e.

    (root)
      └─ c
         └─ a
            ├─ t*
            └─ r*
               ├─ d*
               └─ e*
  5. Insert "do" and "dog"

    These create a new branch from the root under d.

    (root)
      ├─ c
      │  └─ a
      │     ├─ t*
      │     └─ r*
      │        ├─ d*
      │        └─ e*
      └─ d
         └─ o*
            └─ g*

Nodes marked with * are word endings. Notice that "car" and "card" share the path c → a → r -- the shared prefix is stored only once.

The Structure

Each node in a trie contains:

  • Children -- a map from characters to child nodes (up to one per possible character)
  • isEndOfWord -- a boolean flag indicating whether this node completes a valid word

Node structure (pseudocode)

class TrieNode:
    children = {}      // map: character → TrieNode
    isEndOfWord = false

The root node is empty -- it represents the empty prefix that all words share. Each edge in the tree corresponds to one character.

A key property: the trie does not store keys in its nodes. The key is implicit in the path from root to that node. The node for "car" doesn't contain the string "car" -- it's simply the node you reach by following c → a → r from the root.

Search Operation

To search for a word, follow the path character by character from the root. If at any point the next character doesn't exist as a child, the word is not in the trie. If you reach the end of the word, check the isEndOfWord flag.

Searching for "card"

Start at root
  'c' → found, go to child 'c'
  'a' → found, go to child 'a'
  'r' → found, go to child 'r'
  'd' → found, go to child 'd'
  End of word, isEndOfWord = true → FOUND

Searching for "can"

Start at root
  'c' → found, go to child 'c'
  'a' → found, go to child 'a'
  'n' → NOT found among children {t, r}  → NOT IN TRIE

Searching for "ca"

Start at root
  'c' → found, go to child 'c'
  'a' → found, go to child 'a'
  End of word, isEndOfWord = false → NOT A WORD
  (The node exists, but "ca" was never inserted as a word)

Prefix Search

This is where tries truly shine. To find all words with a given prefix:

  1. Navigate to the prefix node

    Follow the path character by character, just like a regular search. If the prefix doesn't exist, return an empty result.

  2. Collect all descendants

    From the prefix node, perform a depth-first traversal. Every node marked as a word ending gives you one matching word.

All words starting with "car"

Navigate: root → c → a → r  (found!)
Collect descendants from 'r':
  'r' is a word ending → "car"
  'r' → 'd' is a word ending → "card"
  'r' → 'e' is a word ending → "care"

Result: ["car", "card", "care"]

The Prefix Search Advantage

Finding the prefix node takes O(p) where p is the prefix length. Collecting descendants takes O(k) where k is the total number of characters in all matching words. This is optimal -- you can't do better than reading the output.

Insert and Delete Operations

Insert

function insert(root, word):
    node = root
    for each character ch in word:
        if ch not in node.children:
            node.children[ch] = new TrieNode()
        node = node.children[ch]
    node.isEndOfWord = true

Walk down the tree, creating nodes as needed. At the end, flip the flag. That's it.

Search

function search(root, word):
    node = root
    for each character ch in word:
        if ch not in node.children:
            return false
        node = node.children[ch]
    return node.isEndOfWord

Prefix Enumeration

function findAllWithPrefix(root, prefix):
    node = root
    for each character ch in prefix:
        if ch not in node.children:
            return []
        node = node.children[ch]

    // DFS to collect all words under this node
    results = []
    collect(node, prefix, results)
    return results

function collect(node, currentWord, results):
    if node.isEndOfWord:
        results.append(currentWord)
    for each (ch, child) in node.children:
        collect(child, currentWord + ch, results)

Delete

Deletion is trickier. You can't just remove the final node -- it might be the prefix of another word. The safe approach:

function delete(root, word):
    deleteHelper(root, word, 0)

function deleteHelper(node, word, depth):
    if depth == length(word):
        if not node.isEndOfWord:
            return false       // word doesn't exist
        node.isEndOfWord = false
        return isEmpty(node.children)

    ch = word[depth]
    if ch not in node.children:
        return false           // word doesn't exist

    shouldDeleteChild = deleteHelper(node.children[ch], word, depth + 1)

    if shouldDeleteChild:
        remove node.children[ch]
        return not node.isEndOfWord and isEmpty(node.children)

    return false

The recursion unwinds from the leaf, pruning nodes that are no longer needed -- but only if they aren't part of another word's path.

Complexity Analysis

OperationTimeNotes
Insert O(m) m = length of the key
Search O(m) Independent of the number of keys stored
Delete O(m) Walk down, then prune back up
Prefix search O(p + k) p = prefix length, k = total output size

Key Complexity Property

Trie operations depend on the length of the key, not on the number of keys stored. Whether your trie holds 100 words or 10 million, searching for "cat" always takes exactly 3 steps. A hash table is O(1) amortized on average, but O(m) in practice for computing the hash -- and it can't do prefix queries at all.

Space Analysis

The space story is more nuanced. In the worst case -- when no words share any prefixes -- every character gets its own node. With n words of average length m over an alphabet of size Σ:

Space trade-offs

Worst case:  O(n × m × |Σ|)  nodes × children-per-node
Best case:   Much less, when prefixes are heavily shared

Example with our 6 words: Total characters across all words: 3+3+4+4+2+3 = 19 Nodes in trie (excluding root): 10 Savings from shared prefixes: 9 characters (47%)

In practice, natural-language dictionaries share prefixes extensively. The English prefixes "un-", "re-", "pre-", "dis-", "over-" each merge thousands of words into shared paths. But for random strings with no common prefixes, tries can be wasteful.

Compressed Tries (Radix Trees)

A standard trie can have long chains of nodes with only one child -- wasting space and memory. A compressed trie (also called a radix tree or Patricia trie) merges these single-child chains into single edges labeled with multi-character strings.

Standard trie vs. compressed trie

Standard trie for ["test", "testing", "team", "tea"]:

(root) └─ t └─ e ├─ s │ └─ t* │ └─ i │ └─ n │ └─ g* └─ a ├─ m* └─ (end)* ← "tea"

Compressed trie (radix tree):

(root) └─ "te" ├─ "st"* │ └─ "ing"* └─ "a"* └─ "m"*

The compressed version has fewer nodes and edges. Each edge stores a string instead of a single character. The operations work the same way, but you compare substrings instead of individual characters.

Radix trees are especially useful for IP routing tables, file system paths, and anywhere keys are long but share significant prefixes.

Where Tries Are Used

Application How it uses a trie
Autocomplete Type a prefix, traverse descendants to get suggestions ranked by frequency
Spell checkers Quickly verify if a word exists; suggest corrections by exploring nearby branches
IP routing Longest prefix match on binary IP addresses -- every router does this millions of times per second
T9 predictive text Map number-key sequences to words; each key press narrows the trie branch
Dictionary compression LZW and similar algorithms build tries of seen substrings to compress data
Genome analysis Suffix tries index DNA sequences for fast substring search across billions of bases

Key Takeaways

  • A trie stores strings in a tree where each edge represents one character and shared prefixes share paths
  • Insert, search, and delete all run in O(m) time where m is the key length -- independent of how many keys are stored
  • Prefix search is where tries beat every other data structure: find the prefix node in O(p), then collect results
  • Hash tables can't efficiently answer "all words starting with X" -- tries can
  • Compressed tries (radix trees) merge single-child chains to save space
  • Tries power autocomplete, spell checking, IP routing, and text prediction in real systems

Try It Yourself -- Trie Explorer

Insert words into a trie and watch it grow. Then type a prefix to see all matching words highlighted in the tree.

Trie Visualization

1
Nodes
0
Words
0
Prefix matches

The trie is a reminder that the right data structure can make an impossible-seeming operation trivial. Hash tables are fast for exact lookups, but when you need to exploit the structure of your keys -- their prefixes, their ordering, their shared parts -- a trie turns a linear scan into a tree walk. It's the data structure that makes your phone's keyboard feel like it can read your mind.