Lesson 6 · Non-linear structures

Tries and Prefix Trees

A trie, or prefix tree, stores strings as paths from a root, one node per letter, so words that share a prefix share those nodes. It answers prefix questions a hash table cannot.

Tries and Prefix Trees concept diagramA visual explanation of the layout and operations shown in this lesson.●catrone node per character"cat" and "car" sharethe prefix "ca"catcar
1

The Path Is the Key

A trie, also called a prefix tree and pronounced 'try', stores strings by their letters. Each edge stands for one character, and the edges from the root down to a node spell a prefix.

No node holds a whole string. The word cat exists only as the path root → c → a → t. A hash table keeps the key and computes where to put it; a trie breaks the key into letters and lets the position be the key.

Words with the same start share the same path. car, card and care all go through the same c, a and r nodes before they split. In the tracer, 5 words with 17 letters fit in 9 nodes.

Each node needs two things: a way to reach its children by character, and an end-of-word flag. The flag matters: after inserting card, the path for car exists too, and only the flag says whether car itself was stored.

Children are kept either in a fixed array (26 slots for lowercase letters, indexed by c - 'a') or in a hash map holding only the children that exist. The array is faster; the map is far smaller when most slots would be empty.

  • The empty string is stored by flagging the root
  • Uppercase, digits or Unicode need a bigger array or a map
  • Duplicate inserts change nothing: the path and the flag already exist
2

Operations at a Glance

Insert walks the word letter by letter, following a child when it exists and creating it when it does not, then flags the last node. Search walks the same way without creating anything and returns the flag. Prefix search does the same walk and ignores the flag.

Delete clears the flag, then removes nodes from the bottom up only while they have no children and end no other word. Each operation is O(L) for a key of length L.

The step-by-step version, with the delete cases and the bugs that break them, is in trie operations. To build one yourself, try Implement Trie (Prefix Tree).

  • Search checks the flag; prefix search does not
  • Listing every word with a prefix costs O(L + k) for k results in the subtree
3

Trie vs Hash Table

Trie operations cost O(L) in the key's length, with no dependence on n, the number of keys. Finding card takes 4 steps in a trie of 5 words or of 5 million.

That is not faster than a hash table for exact lookup. A hash table also reads all L characters to hash the key and again to confirm a match, so it is O(L) too, usually with a smaller constant and far less memory. A balanced BST of strings makes O(log n) comparisons, each up to O(L): O(L log n).

The trie wins on questions a hash table cannot answer. Prefix queries: all words starting with car are the subtree under r, found in O(L + k) for k results, while a hash table must test every key, O(n · L). Sorted order: visiting children a to z lists the keys alphabetically with no sort. Longest prefix match: walking an address bit by bit and remembering the last flagged node is how routers pick a route.

A trie also has no collisions, so no input can push it into a slow worst case.

The price is memory. With a 26-slot array of 8-byte pointers, each node takes over 200 bytes. The tracer's 10 nodes reserve 260 slots and use 9. Ten thousand unrelated words of about 8 letters can need tens of thousands of nodes, around ten megabytes for data a hash table holds in a fraction of that.

Trie, hash table and balanced BST for string keys
TaskTrieHash tableBalanced BST
Exact lookupO(L)O(L), usually fasterO(L log n)
All keys with a prefixO(L + k)O(n · L)O(L log n + k)
Keys in sorted orderFree, by DFSNeeds a sortFree, in-order
Worst caseSame as averageCollisions can degrade itSame as average
MemoryHigh: child slots per letterLowMedium: one node per key
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Prefix treeAnother name for a trie, from the way every node stands for a prefix.
  • Root nodeThe node for the empty prefix; it holds no character.
  • End-of-word flagMarks a node where a stored word ends, as opposed to a prefix of a longer word.

Structure

  • Child pointersAn array of 26 for lowercase letters, or a hash map holding only the children that exist.
  • Shared branchesWords with the same start, such as car and cat, share the nodes for their common letters.
  • O(L) timeInsert and search cost the key's length L, not the number of stored keys.

Applications

  • AutocompleteWalk to the prefix node, then list every word in its subtree.
  • Spell checkingReject a non-word at the first missing letter; suggest close words by walking nearby branches.
  • IP routingBinary tries find the longest matching prefix of an address.
Implementation

Code in Python, C++ and Java

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False


root = TrieNode()
nodes = 0
words = ["car", "card", "care", "cat", "dog"]
for word in words:
    node = root
    for char in word:
        if char not in node.children:
            node.children[char] = TrieNode()
            nodes += 1
        node = node.children[char]
    node.is_word = True

letters = sum(len(w) for w in words)
print(f"{len(words)} words, {letters} letters, {nodes} nodes below the root")
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

struct TrieNode {
    unordered_map<char, TrieNode*> children;
    bool isWord = false;
};

int main() {
    TrieNode root;
    int nodes = 0, letters = 0;
    vector<string> words = {"car", "card", "care", "cat", "dog"};
    for (const string& word : words) {
        TrieNode* node = &root;
        for (char c : word) {
            if (!node->children.count(c)) {
                node->children[c] = new TrieNode();
                nodes++;
            }
            node = node->children[c];
        }
        node->isWord = true;
        letters += word.size();
    }
    cout << words.size() << " words, " << letters << " letters, " << nodes << " nodes below the root\n";
}
import java.util.HashMap;

class Main {
    static class TrieNode {
        HashMap<Character, TrieNode> children = new HashMap<>();
        boolean isWord;
    }

    public static void main(String[] args) {
        TrieNode root = new TrieNode();
        int nodes = 0, letters = 0;
        String[] words = {"car", "card", "care", "cat", "dog"};
        for (String word : words) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (!node.children.containsKey(c)) {
                    node.children.put(c, new TrieNode());
                    nodes++;
                }
                node = node.children.get(c);
            }
            node.isWord = true;
            letters += word.length();
        }
        System.out.println(words.length + " words, " + letters + " letters, " + nodes + " nodes below the root");
    }
}
Watch it run

Step through it

Running on car, card, care, cat, dog

words: car, card, care, cat, dog·trie so farwords0letters stored0nodes below root0
Step 1

An empty trie is one root

A trie starts as a single root that stands for the empty prefix. Each word will become a path down from it, one node per letter, so the letters themselves are never stored as a string.

Output
1 / 12
4

Compressing the Memory Cost

A radix trie, also called a compressed trie or Patricia trie, merges every chain of single-child nodes into one edge with a longer label. Storing only internationalisation takes 20 nodes below the root in a plain trie and one edge in a radix trie. In the tracer, the 5 words drop from 9 nodes to 6.

The cost moves to insertion: a new key that ends or differs partway along an edge forces that edge to split. Inserting do into a radix trie holding dog splits the dog edge into do and g. Linux's IPv4 routing table uses a path- and level-compressed trie of this kind.

A ternary search trie gives each node one character and three children: less, equal and greater. Memory is close to a BST's, prefix queries still work, and a lookup costs about O(L + log n).

For a word list that never changes, a DAWG (directed acyclic word graph) merges shared endings as well as shared beginnings, often shrinking a dictionary by an order of magnitude. It cannot take new words, so it suits fixed word lists such as a spell checker's.

A binary trie stores numbers bit by bit, highest bit first. It answers 'which stored number gives the largest XOR with x' by preferring the opposite bit at each level, in O(bits).

  • Tight on memory: compress to a radix trie before giving up on a trie
  • All substrings of one text: see suffix trees, which start from a suffix trie
  • Related: hash tables, strings