TL;DR
A trie is a tree for storing a set of strings. The root stands for the empty string, each edge adds one letter, and each path from the root spells a prefix. Words that start the same way share their first nodes, so the tree is a compact way to hold a dictionary and to ask "which words begin with these letters?" Finding a word takes time proportional to its length, not to the number of words stored.
Builds on: Binary Tree · Leads to: Radix Tree, a compressed trie that merges single-child chains, and prefix search in many systems.
Where it's used
Autocomplete in search boxes. When you type "ca" in a search box, the system wants the stored queries that start with "ca". A trie lets it walk two edges down and then list every word in that subtree. The walk costs two steps however many millions of queries are stored.
Spell checking and dictionaries. A dictionary stored as a trie answers "is this word in the list?" by following one edge per letter. It can also list the words that are one edit (one insertion, deletion or substitution) away from a misspelling by exploring nearby branches, which a flat list cannot do cheaply.
IP routing. Routers choose where to send a packet by finding the route whose network prefix matches the destination address the longest. Routing tables are stored in tries over the bits of the address, and the router follows the bits until no longer prefix matches. Real routers usually use a compressed form of this idea, which keeps the walk short and the table small.
How it works
Take a tiny set of words: "tea", "ten", "to" and "inn". Here is how the trie is built, one word at a time, and then queried.
flowchart TD R["root"] --> T["t"] R --> I["i"] T --> E["e"] T --> O["o (word: to)"] E --> A["a (word: tea)"] E --> N["n (word: ten)"] I --> N2["n"] N2 --> N3["n (word: inn)"]
-
Start with an empty root. The root has no letter; it stands for the empty string. Check: the root spells "", which is not one of our words.
-
Insert "tea". Read the first letter, "t". The root has no edge for "t", so create one and move to the new node. Repeat for "e" and "a". Mark the last node as the end of a word. Check: three new nodes, and the node for "a" is marked.
-
Insert "ten". Start at the root and follow "t" and "e", which already exist, so no new nodes are needed for those letters. The next letter is "n", which the "e" node does not have. Create it and mark it as the end of a word. Check: only one new node, because "te" was shared.
-
Insert "to". Follow "t". The "t" node has no edge for "o", so create it and mark it as the end of a word. Check: one new node. Two words now share the path "t".
-
Insert "inn". No edge from the root for "i" exists, so the path "i", "n", "n" is all new. Mark the last "n" as the end of a word. Check: three new nodes, and the tree now holds four words in 8 nodes plus the root.
-
Look up "ten". Follow "t", "e", "n". All three edges exist, and the final node is marked as a word, so "ten" is in the set. Check: three steps for a three-letter word.
-
Look up "te". Follow "t" and "e". Both edges exist, so "te" is a prefix of some stored word. But the "e" node is not marked, so "te" is not itself a word. Check: the prefix test and the word test are separate questions, and the trie answers both.
-
Find all words starting with "te". Walk to the "e" node in two steps, then collect every marked node below it: "tea" and "ten". Check: the answer is the subtree under the prefix, so nothing outside it is visited.
The math
Let the alphabet have size s, so each node has at most s children. Let the stored words have total length M, counting all letters.
A trie for a set of strings W over an alphabet is a rooted tree in which each edge is labelled with one letter, no two edges leaving the same node have the same letter, and a node is marked as an end point exactly when the string spelled from the root to it is in W.
Step 2 in symbols: how many nodes
Every node except the root is created while inserting some word, and each created node corresponds to one new letter position in some word. So the number of nodes is at most M + 1. Shared prefixes make it smaller. In the example, the words have 3 + 3 + 2 + 3 = 11 letters in total, and the tree has 8 non-root nodes, because the "t" and "e" of "ten" and the "t" of "to" reuse nodes that already exist.
Step 6 in symbols: the cost of a lookup
A word of length L is found by following L edges, one per letter. If each node finds its child in constant time, as with an array indexed by letter, the lookup costs steps (big-O notation counts how cost grows with input size). This does not depend on how many words are stored. A Hash Table also needs to read the whole word to hash it, so its cost is also on average, but a comparison-based Binary Search over sorted strings costs for n words, because each comparison may read many letters.
Step 8 in symbols: a prefix query
A prefix p of length L is found in O(L) steps. The answer is the set of marked nodes in the subtree below that node. If the subtree holds k words, the query visits at most the nodes on the paths to those words, so its cost is O(L + total length of the k answers).
Worked examples
Store "cat" and "car".
- Insert "cat": create nodes c, a, t. Mark t. The tree has 3 nodes below the root.
- Insert "car": follow c and a, which exist. Create r and mark it. The tree has 4 nodes below the root.
- Look up "cat": follow c, a, t. The t node is marked, so the answer is yes.
- Look up "ca": follow c and a. The a node is not marked, so "ca" is a prefix but not a word.
- Count the words starting with "ca": the subtree under a holds two marked nodes, so the answer is 2.
Interpretation: the shared "ca" is stored once, which is why the second word cost only one new node.
Suppose a dictionary has 10,000 words, averaging 8 letters, so the total letter count is M = 80,000. Each node uses an Array of s = 26 child slots for the letters a to z.
- A lookup for an 8-letter word follows 8 edges, so it costs 8 steps.
- A sorted list with binary search would need about log2(10,000), about 13.3 (log base 2), comparisons, and each comparison reads letters until the words differ. So the list needs about 14 comparisons, and many of them read several letters.
- The trie has at most M + 1 = 80,001 nodes. Shared prefixes make the real count much smaller, because English words share many beginnings.
- Each node holds 26 slots, so the array form needs memory for 26 slots per node, which can be large even when most slots are empty.
- Conclusion for lookup: the trie uses 8 steps regardless of dictionary size, while binary search grows with log n. Conclusion for memory: a trie with array children pays for empty slots.
Interpretation: the trie wins on speed for prefix-heavy work and loses on memory unless the children are stored more compactly.
A router holds a few routes, each a bit-prefix of an IP address. Take three routes: 1 (prefix "1"), 10 (prefix "10") and 101 (prefix "101"). An incoming address is 1011, four bits long.
- Start at the root and read the first bit, 1. The node for "1" exists, and it has a route. Remember it as the best match so far: route "1".
- Read the second bit, 0. The node for "10" exists and has a route. Update the best match to route "10".
- Read the third bit, 1. The node for "101" exists and has a route. Update the best match to route "101".
- Read the fourth bit, 1. The table has no node for "1011", so the walk stops. The best match is "101", the longest prefix.
- Send the packet to the route for "101".
Interpretation: following the bits of the address down the trie finds the longest matching prefix in at most as many steps as the address has bits, which is why routers use this structure.
Try it: the same table has routes "1", "10" and "101", and the address is 1100. Which route wins, and why? Answer: route "1". The walk reads 1, which matches route "1". The next bit is 1, but the table has no node "11", because the only route under "1" starts with "10". The walk stops, so the best match is route "1".
Common mistakes and tradeoffs
It is tempting to think that each node stores a letter. In fact the letter lives on the edge that leads to the node, or equivalently in the index of a child array. Storing letters in nodes is a common way to write the code, but the meaning is the same.
It is tempting to think that finding a prefix means the prefix is a word. In fact the two questions differ, which is why the end-of-word mark is needed. Without it, looking up "te" would wrongly say the word "te" is stored.
It is tempting to think a trie always beats a hash table. In fact a Hash Table is usually simpler and uses less memory for exact-match lookups alone. A trie is the better choice when you need prefix search, sorted order, or the words near a given one. Its costs are memory, from child pointers, and the work of walking one node per letter.
When to use a trie: when the work involves prefixes, autocomplete, or many lookups that share beginnings. When not to: when you only need exact lookups over large keys, or when the alphabet is large and the strings are sparse. Alternatives: a hash table for exact lookups, a sorted array with binary search for ordered queries, and a compressed trie, the Radix Tree, when long single-child chains waste nodes.
History
Early computer searches of files and dictionaries used sorted lists and simple trees. In 1959, René de la Briandais described storing a file as a tree of letters, so that a search could start where the last one left off. In 1960, Edward Fredkin introduced the name "trie", taken from the middle of the word "retrieval", and the structure became standard for dictionary and prefix problems. Compressed forms that merge single-child chains followed, and they are the basis of the radix trees used in later systems.
Recap
- A trie stores strings by sharing common beginnings, one letter per edge.
- A word is marked at the node that ends it, so prefixes and whole words are different questions.
- Lookup costs one step per letter, independent of how many words are stored.
- Prefix queries are answered by the subtree under the prefix.
- Memory is the main cost, so compressed tries exist; read next Radix Tree for the compressed form, and Tree Search for the general way of walking a tree.
Check yourself
QuestionA trie holds the words 'dog' and 'do'. How many nodes below the root does it have, and which nodes are marked as words?Show answer
The nodes are d, o, g, so 3 nodes below the root. The marked nodes are the "do" node, which ends the word 'do', and the "dog" node, which ends 'dog'.
QuestionLook up 'carp' in a trie holding 'car' and 'cat'. How many edges does the lookup follow, and what is the answer?Show answer
It follows c, a and r, which is 3 edges. The node for "car" has no edge for 'p', so the lookup stops and the answer is no. The node for 'car' is marked, but 'carp' is not a stored word.
QuestionWhy does a lookup in a trie cost the same for a dictionary of 100 words as for one of 100,000 words, when a [[binary-search|binary search]] does not?Show answer
The trie follows one edge per letter of the search word, so the cost depends only on the word's length. Binary search makes about log n comparisons, which grows as the list grows, and each comparison may read several letters.
QuestionAn autocomplete system must show every stored query that starts with 'ap'. Describe the steps, and say what the cost depends on.Show answer
Follow the edges for a and p from the root. If the node exists, collect every marked node in its subtree. The cost is the two steps to reach the prefix plus the work of visiting the answers, so it depends on the prefix length and the number of answers, not on the total number of stored queries.
QuestionA team stores short product codes that are all the same length and only need exact lookup. Should they use a trie? Give a reason.Show answer
Probably not. A Hash Table gives exact lookups with less memory and simpler code, and the trie's prefix and ordering features are not needed. A trie would be worth considering only if the team later needs prefix search over the codes.