Simple Algorithm
Algorithms & Data Structures · Optimized · 20 min

Tries

Prefix trees for dictionaries, autocomplete and bitwise queries.

Type "alg" into a search box and suggestions appear before you finish the word. A hash table can tell you whether "algorithm" is in its dictionary, but not which stored words begin with "alg". A trie answers both questions in time proportional to the length of what you typed, whether it holds a hundred words or a hundred million.

What you’ll learn

  • Build a trie and implement insert, search, prefix counting, autocomplete and deletion, each in O(L)O(L) steps for a key of length LL, plus the size of any output.
  • Prove the trie invariant by induction, and bound the number of nodes by the total length of the stored words.
  • Choose a child representation (array, hash map, sorted list, ternary search trie) from the alphabet size and the memory budget.
  • Recognize trie problems in a statement, including integers under XOR, and tell them apart from look-alikes that need a hash set or a suffix structure.

One node per prefix

A trie stores a set of strings as a rooted tree whose edges are labeled with characters. The children of a node carry distinct labels, so every node vv spells a unique string str(v)\mathrm{str}(v) along the path from the root, and str(v)\mathrm{str}(v) is a prefix of every word stored below vv. A flag marks the nodes where a stored word ends.

To insert a word, walk down from the root along its characters, creating each missing edge; to search, walk the same way and fail at the first missing edge. Neither operation looks at any other word, which is why the cost does not depend on how many words are stored.

Predict before you look

How many nodes, counting the root, does the trie of the five words car, card, care, cart and cat have?

Show the answer

8

The distinct nonempty prefixes are c, ca, car, card, care, cart and cat: seven nodes, plus the root. The words have 18 characters in total, but each shared prefix is stored once, so the bound 1+∑∣w∣=191 + \sum \abs{w} = 19 is far from tight here.

Every operation in O(L)

Two counters per node make prefix questions free: end[v] counts the stored words that end at vv, and cnt[v] counts the stored words that pass through vv, which by the invariant is the number of stored words that start with str(v)\mathrm{str}(v). Children live in a dictionary from character to node index.

python
class Trie:
    def __init__(self):
        self.kids = [{}]          # kids[v]: character -> child node
        self.end = [0]            # number of stored words that end at v
        self.cnt = [0]            # number of stored words that pass through v

    def insert(self, word):
        v = 0
        self.cnt[0] += 1
        for ch in word:
            if ch not in self.kids[v]:
                self.kids[v][ch] = len(self.kids)
                self.kids.append({}); self.end.append(0); self.cnt.append(0)
            v = self.kids[v][ch]
            self.cnt[v] += 1
        self.end[v] += 1

    def walk(self, s):            # the node spelling s, or None
        v = 0
        for ch in s:
            v = self.kids[v].get(ch)
            if v is None:
                return None
        return v

    def contains(self, word):
        v = self.walk(word)
        return v is not None and self.end[v] > 0

    def count_prefix(self, p):    # stored words that start with p
        v = self.walk(p)
        return 0 if v is None else self.cnt[v]

Nodes are integers indexing parallel lists, which is faster and lighter in Python than one object per node. Inserting a word twice increments end, so the trie stores a multiset; use a flag instead if duplicates must be ignored.

python
def complete(t, p, k):            # the first k stored words starting with p, in order
    out, v = [], t.walk(p)
    def dfs(u, s):
        if t.end[u] and len(out) < k:
            out.append(s)
        for ch in sorted(t.kids[u]):
            if len(out) == k:
                return
            dfs(t.kids[u][ch], s + ch)
    if v is not None:
        dfs(v, p)
    return out

Autocomplete is a walk to the prefix's node followed by a depth-first search below it, visiting children in alphabetical order. With the eight words above, complete(t, "t", 4) returns tea, team, ten, to.

OperationCostHow
insert, search a word wwO(∣w∣)O(\abs{w})one step per character; insert creates at most ∣w∣\abs{w} nodes
count words with prefix ppO(∣p∣)O(\abs{p})walk to pp's node and read cnt
list completions of ppO(∣p∣)O(\abs{p}) + the subtree exploredDFS below pp's node; store the best kk completions in each node to get O(∣p∣+k)O(\abs{p} + k) at the price of memory
delete ww (stored)O(∣w∣)O(\abs{w})decrement cnt along the path and end at its last node; nodes whose cnt drops to 0 may be freed
all words in sorted orderOO(number of nodes)DFS with children in alphabetical order: this is MSD radix sort in disguise
"One step" is O(1)O(1) in the worst case with array children and O(1)O(1) expected with hash-map children; the number of stored words never appears.
Check your understanding

A trie holds 10610^6 words of lengths up to 20. How many nodes does count_prefix("alg") visit after the root?

  1. About log⁡2106≈20\log_2 10^6 \approx 20
  2. At most 60, three characters times the maximum length
  3. 3
  4. Up to 10610^6, one per stored word
Show the answer

C. 3

The walk follows one edge per character of the prefix and then reads the counter stored at that node: three steps, whatever the number or length of the stored words. That independence from nn is the point of a trie.

Memory: how a node stores its children

A trie trades memory for speed: it can need one node per stored character, so the total length of the words, not their number, sizes it. What each node costs depends on how it stores its children, and the right choice depends on the alphabet.

Children stored asOne stepMemory per nodeUse when
array of ∣Σ∣\abs{\Sigma} child indicesO(1)O(1) worst case∣Σ∣\abs{\Sigma} slots even in a leaf: 26×4=10426 \times 4 = 104 bytessmall alphabets, contest code, maximum speed
hash mapO(1)O(1) expectedproportional to the children, plus a large constantlarge or open alphabets: Unicode text, word tokens
sorted array of (character, child)O(log⁡∣Σ∣)O(\log \abs{\Sigma})proportional to the childrenstatic tries built once and queried often
ternary search triea few comparisons per characterthree links per nodelarge alphabets on a budget (Bentley & Sedgewick, 1997)
compressed edges (radix tree)compares a substring per edgeat most 2k2k nodes for kk wordslong words with few branch points
A ternary search trie keeps a small binary search tree of characters at each position: each node holds one character and links to "less", "equal" (the next position) and "greater".
cpp
#include <string>

const int MAXN = 1000001;    // total characters inserted + 1 for the root
int nxt[MAXN][26], cnt[MAXN], ends_here[MAXN], nodes = 1;   // node 0 is the root

void insert(const std::string& w) {
    int v = 0;
    cnt[v]++;
    for (char ch : w) {
        int c = ch - 'a';
        if (!nxt[v][c]) nxt[v][c] = nodes++;   // index 0 doubles as "no child"
        v = nxt[v][c];
        cnt[v]++;
    }
    ends_here[v]++;
}

int count_prefix(const std::string& p) {
    int v = 0;
    for (char ch : p) {
        v = nxt[v][ch - 'a'];
        if (!v) return 0;
    }
    return cnt[v];
}

The contest idiom: global arrays sized by the total input length, not by the number of words. With 10610^6 characters the child table alone is 104 MB, so check the memory limit first. In multi-test problems, clear only the nodes entries you used between test cases.

Recognizing it

Reach for a trie when a problem has these signals:

  • many strings and questions about prefixes: "starts with", autocomplete, "how many words begin with pp?";
  • a dictionary consulted while a string grows one character at a time: grid word searches, segmenting a string into words, streams of characters; the trie lets you stop the moment the current string is no longer a prefix of any word;
  • the longest (or shortest) stored prefix of a query: routing tables, replacing words by their roots;
  • integers and XOR: a binary trie over the bits, from the most significant down.
ProblemKey ideaCost
Insert nn words, then answer "how many words start with pp?" or list thempass counters; DFS below pp's nodeO(total length+∑∣p∣)O(\text{total length} + \sum \abs{p}), plus the output
Word search in a grid: which of many dictionary words can be traced through adjacent cells?DFS from each cell while walking the trie in step; abandon a path as soon as it leaves the trie, and unmark words once foundthe trie prunes every path that is not a prefix of some word
Replace each word of a sentence by its shortest dictionary rootwalk the word down the trie and stop at the first marked nodeO(total length)O(\text{total length})
Word break: can ss be split into dictionary words?DP over positions; from each reachable ii, walk the trie along s[i..]s[i..] and mark each jj where a word endsO(n⋅Lmax⁡)O(n \cdot L_{\max}) trie steps
The maximum XOR of two numbers in an arraybinary trie of the numbers, greedy descent toward the opposite bitO(nw)O(n w) for ww-bit numbers
Lmax⁡L_{\max} is the length of the longest dictionary word. In word break, each walk stops after at most Lmax⁡L_{\max} characters, instead of hashing all O(n2)O(n^2) substrings.
Check your understanding

For which of these problems does a trie not help?

  1. Suggest the stored words that complete a typed prefix
  2. Find the longest stored network prefix of an IP address
  3. Find the longest palindromic substring of a single string
  4. Count the stored words that start with a given string
Show the answer

C. Find the longest palindromic substring of a single string

Palindromes are about a string's symmetry around a center, not about prefixes of stored words; expanding around each center, or Manacher's algorithm (see Palindromes: Manacher's Algorithm & the Eertree), is the tool. The other three are prefix questions over a stored set: a trie's home ground.

Bitwise tries for integers

An integer below 2w2^w is a string of ww bits. Insert numbers into a binary trie from the most significant bit down, and every number becomes a root-to-leaf path of length ww. To find the stored yy that maximizes x⊕yx \oplus y (xor), walk down from the root and at each bit take the child opposite to xx's bit whenever it exists, since that sets this bit of the XOR to 1.

Greed is safe here because a bit outweighs everything below it:

2b  >  2b−1+2b−2+⋯+2+1  =  2b−12^b \;>\; 2^{b-1} + 2^{b-2} + \cdots + 2 + 1 \;=\; 2^b - 1
Two numbers compare like their bit strings, from the top: the highest bit where they differ decides. So a 1 in bit bb of the XOR beats any combination of lower bits.
BitBit of x=8=10002x = 8 = 1000_2Wanted childExists?Bit of x⊕yx \oplus yCandidates left
310yes11, 4, 5
201yes14, 5
101no: forced to 004, 5
001yes15
The trie stores {1,4,5,12}={0001,0100,0101,1100}2\{1, 4, 5, 12\} = \{0001, 0100, 0101, 1100\}_2. The descent returns 11012=13=8⊕51101_2 = 13 = 8 \oplus 5, and indeed 8⊕1=98 \oplus 1 = 9, 8⊕4=128 \oplus 4 = 12 and 8⊕12=48 \oplus 12 = 4 are all smaller.
python
def max_xor_pair(nums, w=30):     # at least two integers in [0, 2^w)
    kids = [[0, 0]]               # node 0 is the root; child index 0 means "none"
    def insert(x):
        v = 0
        for b in range(w - 1, -1, -1):
            bit = (x >> b) & 1
            if not kids[v][bit]:
                kids[v][bit] = len(kids)
                kids.append([0, 0])
            v = kids[v][bit]
    def query(x):                 # max of x ^ y over the stored y
        v, res = 0, 0
        for b in range(w - 1, -1, -1):
            want = 1 - ((x >> b) & 1)
            if kids[v][want]:
                res |= 1 << b
                v = kids[v][want]
            else:
                v = kids[v][1 - want]
        return res
    insert(nums[0])
    best = 0
    for x in nums[1:]:
        best = max(best, query(x))   # pair x with every earlier number
        insert(x)
    return best

O(nw)O(n w) time and at most nw+1n w + 1 nodes, against (n2)\binom{n}{2} XORs for checking every pair. Querying each number before inserting it pairs it with all earlier ones, so every pair is considered once.

Think first The minimum XOR of two numbers in an array needs no trie: sort, and take the smallest XOR of neighbors. Why does the same trick fail for the maximum?

A small XOR needs a long common prefix of bits, and in sorted order the numbers sharing the longest prefixes with xx sit next to it: for a<b<ca < b < c, a⊕c≥min⁡(a⊕b, b⊕c)a \oplus c \ge \min(a \oplus b,\ b \oplus c). A large XOR needs the opposite: a partner that differs from xx as high up as possible and then, among those, keeps differing, and such a partner can be anywhere in sorted order. The trie finds it bit by bit.

Key takeaways

  • A trie has one node per distinct prefix; insert, search and prefix counting cost O(L)O(L) for a key of length LL, independent of the number of stored words.
  • Two counters per node, words ending here and words passing through, answer "is it stored?" and "how many start with pp?" and make deletion a matter of decrementing.
  • Memory is the price: up to one node per stored character, times the cost of a node's child table. Choose arrays, hash maps or sorted lists by alphabet size and budget.
  • Recognize it by prefixes over a set of strings, a dictionary consulted while a string grows, longest-prefix matches, and XOR over integers; text search with many patterns needs Aho–Corasick, and many queries on one text need a suffix structure.
  • A binary trie answers "maximize x⊕yx \oplus y" greedily from the top bit in O(w)O(w), so the maximum XOR pair takes O(nw)O(n w) instead of O(n2)O(n^2).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A trie holds "car" and "care". How many new nodes does inserting "card" create, and how many does inserting "ca" create afterwards?

  1. 4 and 2
  2. 1 and 0
  3. 1 and 2
  4. 0 and 0
Show the answer

B. 1 and 0

"card" shares the path c, ca, car and needs one new node for "card". "ca" is already a path in the trie, so inserting it only marks the existing node as the end of a word.

Question 2

A trie stores "tea" and "ten" but its nodes carry no end-of-word marks: search reports "found" whenever the walk succeeds. Which query does it answer wrongly?

  1. Searching for "tea"
  2. Searching for "tex"
  3. Counting the words that start with "te"
  4. Searching for "te"
Show the answer

D. Searching for "te"

The walk along "te" succeeds because "te" is a prefix of both words, so a trie without marks reports a word that was never inserted. The mark (or the counter end) is what separates stored words from mere prefixes.

Question 3

Your trie stores 3×1053 \times 10^5 words of length at most 10 over the 26 lowercase letters, with a 26-entry array of 4-byte indices in every node. What is the worst-case memory of the child arrays?

  1. About 31 MB
  2. About 312 MB
  3. About 3 MB
  4. About 31 GB
Show the answer

B. About 312 MB

There can be up to 3×106+13 \times 10^6 + 1 nodes, one per character plus the root, and each array takes 26×4=10426 \times 4 = 104 bytes: about 3.1×1083.1 \times 10^8 bytes, or 312 MB. That is over most contest memory limits, which is why the node count bound matters before you allocate.

Question 4

In a binary trie, the maximum-XOR query takes the child opposite to xx's bit at the highest level where that child exists, without looking further down. Why can this never cost the optimum?

  1. Because XOR is commutative and associative
  2. Because a 1 in bit bb of the result is worth 2b2^b, more than all lower bits together, 2b−12^b - 1
  3. Because the trie keeps the numbers in sorted order
  4. Because each number has a unique path, so there is only one candidate at each level
Show the answer

B. Because a 1 in bit bb of the result is worth 2b2^b, more than all lower bits together, 2b−12^b - 1

Numbers compare by their highest differing bit. Any partner that makes bit bb of the XOR 0, when another partner sharing the same higher bits makes it 1, loses whatever happens below. By induction from the top, the greedy path gives the maximum.

Question 5

You build a trie over sentences, treating each word as one symbol: about 10510^5 distinct symbols, and most nodes have one or two children. How should a node store its children?

  1. An array with one slot per symbol, for O(1)O(1) worst-case steps
  2. A hash map, or a sorted array if the trie is static
  3. A linked list of all 10510^5 symbols
  4. Children are not needed: store the sentences in a hash set
Show the answer

B. A hash map, or a sorted array if the trie is static

With a huge, sparse alphabet, per-node arrays would hold 10510^5 mostly empty slots in every node. A hash map stores only the children that exist, with O(1)O(1) expected steps; a sorted array is even leaner when no insertions follow, at O(log⁡fan-out)O(\log \text{fan-out}) per step.

Go deeper

Further reading

  • E. Fredkin, "Trie memory," Communications of the ACM 3(9) (1960), 490–499.
  • R. de la Briandais, "File searching using variable length keys," Proceedings of the Western Joint Computer Conference (1959), 295–298.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 5.2 (tries and ternary search tries).
  • D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.3 (digital searching).