A trie, or prefix tree, is a tree data structure that stores words one character per node, so words that start with the same letters share those nodes. Inserting, finding or deleting a word walks one path as long as the word, however many words the trie holds. This page explains how it works, with step-by-step animations of insertion, deletion and autocomplete from the VisiGrab app.
// how tries work
A trie is a tree data structure that stores words one character per node. A word is the path from the root down to a node marked as the end of a word. Words that start with the same letters share the nodes for those letters, so a trie is also called a prefix tree.
The name comes from retrieval. Edward Fredkin coined it in 1960 and pronounced it "tree". Many people, and the app, say "try" to tell it apart.
A node holds one character, its children keyed by character, and an end-of-word flag. It stores no word and no count. In the app's code, each node also links to its parent, which deletion uses to walk back up.
The root is a sentinel with no character; each word's first letter is one of its children. The app's step-by-step views leave the root out, and so do this page's animations: their top row is the root's children. The figure below draws and labels the root, as one of the app's info pictures does.
The flag tells a stored word apart from a path that only leads to a longer one. Without it, a stored cat looks the same as the cat inside catch. So a flagged node is not always a leaf: t can end cat and still lead on to catch.
Many textbooks give each node an array of 26 links, one per lowercase letter. A child is found in one step and the children come out in alphabetical order, but most slots stay empty. A map, hashed or sorted, stores only the children that exist and accepts any character, but each lookup costs a hash or a few comparisons. The app's code uses dict in Python, HashMap in Java and std::map, a sorted tree, in C++.
The full source code is on GitHub, in Python, Java and C++.
Insertion walks the word from the root. If a node for the next character exists, the walk continues into it; if not, a new node is created, and so is every node after it. Then the last node is marked as end-of-word.
Here cabin is inserted into the trie of cab, cat and catch. The walk continues through the existing c, a and b. New nodes i and n are created below b, and n is marked as the end of cabin: two new nodes for five letters.
Inserting a prefix of a stored word creates no nodes: with only catch stored, inserting cat just flags t.
Search walks the word and fails if the path breaks or its last node has no flag. In the cab, cat and catch trie, a search for cat ends at the flagged t: found. A search for ca ends at the a node, which has no flag: ca is a path, not a word. A search for cap fails at the a node, which has no p child.
The startsWith of LeetCode 208 skips the flag check. After inserting only apple, search("app") is false and startsWith("app") is true. In the app's code, startsWith returns the matching words themselves, not true or false: that is the autocomplete below.
Autocomplete walks the prefix; if a character is missing, there are no matches. Otherwise a depth-first search (DFS) below the prefix's last node collects every flagged node, that node included. The DFS keeps a path buffer: it adds a character on the way down, removes it on the way back, and copies the buffer out at each flagged node.
Here the trie holds cab, cabin, car, cat, catch, tip and top, and the prefix is ca. The flagged nodes below the a node are b, n, r, t and h, so the matches are cab, cabin, car, cat and catch. The root's other child, t, leads to tip and top and is never visited.
The DFS gives alphabetical (lexicographic) order only if it visits children in character order, as an array or std::map does. A Java HashMap guarantees no order and a Python dict keeps insertion order, so their matches need sorting. The app sorts its matches before showing them.
Deletion walks to the word's last node and clears its flag. Then the walk goes back up the parent links, removing every node with no flag and no children. It stops at the first node that still ends a word or has another child.
| Word deleted | Also stored | Nodes removed |
|---|---|---|
| cat | cab, catch | none; t is only unmarked |
| catch | cab, cat | h and the second c |
| cab | cat | b only |
| cab | nothing else | c, a and b; the trie is empty |
Here cat is deleted from the trie of cab, cat and catch. The walk goes c, a, t. The t node still leads on to catch, so it is only unmarked, and all six nodes stay.
Here catch is deleted from the same trie. The walk goes c, a, t, c, h. Once unmarked, h has no flag and no children. Without h, the second c has neither, so both are removed in one step. The t node still ends cat, so pruning stops there, and cab and cat remain.
A lazy delete only clears the flag and leaves dead branches: LeetCode's startsWith("catc") then stays true with catch gone. The app's code prunes in a loop up the parent links; textbooks often use recursion.
When you need prefix or order queries: a trie lists the words that start with a prefix without touching the others, finds the longest stored prefix of a string in one walk and, with its children in character order, lists its words sorted. For exact lookups alone, a hash set is usually faster and smaller. The second player shows a prefix query.
Here L is the length of the word or prefix, N the number of stored words, and K the number of matches a prefix query returns. Insert, search, delete and a true-or-false startsWith each walk one path of L characters, so their cost does not grow with N.
| Operation | Time |
|---|---|
| Insert | O(L) |
| Search | O(L) |
| Delete | O(L) |
| startsWith, true or false | O(L) |
| Autocomplete, list the matches | O(L + K) |
O(L + K) counts one step per match. Strictly, the DFS visits every node below the prefix and copies out each word: L plus the total length of the matches. Each bound treats finding a child as one step.
A trie has one node per distinct prefix of its words. That is at most the total number of characters, O(N × L) for N words of length up to L, reached when no prefix is shared. With an array of σ links per node, where σ is the alphabet size (26 above), the links take O(σ × N × L). Real vocabularies share beginnings, so a trie is usually far smaller.
For exact lookup alone, a small word list or tight memory, use a hash set: it is usually faster and smaller. A trie wins on prefix and order queries. It lists the words with a prefix without touching the rest; a hash set checks every word. It finds the longest stored prefix of a string in one walk; a hash set needs one lookup per prefix. With children in character order, it also lists its words sorted, with no separate sort.
A binary search tree of strings keeps each whole key in one node, so it shares no prefixes. A balanced one makes O(log N) comparisons of up to L characters, so a lookup costs O(L log N), against O(L) in a trie. A sorted tree such as the red-black tree behind Java's TreeMap can also list the words with a prefix: a range scan in O(L log N) plus the matches.
A radix tree, or compressed trie, merges each chain of single-child nodes that end no word into one edge labeled with a string. In the cab, cat and catch trie, c-a becomes ca, and the c-h below t becomes ch. It needs fewer nodes when words have long parts that no other word shares. A Patricia trie is a radix tree over bits. A ternary search tree gives each node three links, for smaller, equal and larger characters, which saves memory on large alphabets.
// in the app
In VisiGrab you build the trie yourself, and every change plays out step by step.
Insert words, delete them, or find every word with a prefix, each step by step. Or start from a random trie.
Step through every walk, and step back through it: removed nodes come back.
Twenty words to build with, from cab and cat to carriage and topology, and ten prefixes to search.
The root, shared prefixes, the end-of-word flag and the cost of every operation, illustrated.
A trie implementation with insert, search, delete and startsWith, explained part by part.
Check what you have learned before moving on.
// build your own
Download VisiGrab and step through every insertion, deletion and prefix search yourself.
The trie is one of 30+ topics. See them all