Trie, step by step.

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 a trie works

What is a trie (prefix tree)?

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.

Trie node structure and the root

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.

A trie drawn below a circle labeled root. Under the root is c, under c is a, and a has two children, b and t. Under t is a second c, and under that is h. The nodes b, t and h are filled: they end the words cab, cat and catch.
The trie of cab, cat and catch, with the root drawn: c and a are shared by all three words, and the filled nodes b, t and h each end one.

The end-of-word flag: why a flagged node need not be a leaf

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.

Two tries side by side, each a single path c, a, t, c, h. In the left trie only h is filled, so only catch is stored. In the right trie both t and h are filled, so cat and catch are stored.
The same c-a-t-c-h path twice: on the left t is only a waypoint to catch; on the right t also ends cat.

Trie children: array of 26, hash map or sorted map

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++.

Trie insertion: shared prefixes share nodes

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.

Insert cabin

All steps as text
  1. The word cabin is selected for insertion. Step forward to insert it.
  2. Since character c already exists, continue traversal.
  3. Since character a already exists, continue traversal.
  4. Since character b already exists, continue traversal.
  5. Create a new node for i — this character isn't in the trie yet.
  6. Create a new node for n — this character isn't in the trie yet.
  7. Mark this node as end-of-word for cabin.
Trie — Insert cabin. Last step: The trie holds cab, cabin, cat and catch; the blue nodes mark where each word ends.

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.

Prefix search and autocomplete with a trie

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.

Starts with ca

All steps as text
  1. The prefix ca is selected. Step forward to find every word that starts with it.
  2. Prefix highlighted: ca.
  3. Matches found: cab, cabin, car, cat, catch.
Trie — Starts with ca. Last step: Matches found: cab, cabin, car, cat, catch.

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.

Deleting a word from a trie

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 deletedAlso storedNodes removed
catcab, catchnone; t is only unmarked
catchcab, cath and the second c
cabcatb only
cabnothing elsec, 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.

Delete cat

All steps as text
  1. The word cat is selected for deletion. Step forward to delete it.
  2. Traverse to character c.
  3. Traverse to character a.
  4. Traverse to character t.
  5. The red node will be unmarked as end-of-word; the rest stay as shared prefixes.
  6. Unmark t as end-of-word for cat — it stays in the trie as a prefix for other words.
Trie — Delete cat. Last step: cat is gone, and t stays as part of catch; the trie holds cab and catch.

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.

Delete catch

All steps as text
  1. The word catch is selected for deletion. Step forward to delete it.
  2. Traverse to character c.
  3. Traverse to character a.
  4. Traverse to character t.
  5. Traverse to character c.
  6. Traverse to character h.
  7. Red nodes will be removed; the rest stay as shared prefixes.
  8. Unmark h as end-of-word and remove the red nodes.
Trie — Delete catch. Last step: catch is gone; the trie holds cab and cat.

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 should you use a trie instead of a hash table?

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.

Trie time complexity

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.

OperationTime
InsertO(L)
SearchO(L)
DeleteO(L)
startsWith, true or falseO(L)
Autocomplete, list the matchesO(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.

Trie space complexity

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.

Trie vs hash table

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.

Trie vs binary search tree

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.

Radix tree, Patricia trie and other trie variants

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.

Where tries are used: autocomplete, spell checking and IP routing

  • Autocomplete: the suggestions come from the subtree below the typed prefix.
  • Spell checking: near-matches come from allowing small edits during the walk.
  • T9 and predictive text: the trie keeps only the letter sequences that begin a real word.
  • IP routing: longest-prefix match walks a binary trie of address bits and keeps the last route it passed.

Four examples here.
The whole topic in the app.

In VisiGrab you build the trie yourself, and every change plays out step by step.

Your own trie

Insert words, delete them, or find every word with a prefix, each step by step. Or start from a random trie.

Forward and back

Step through every walk, and step back through it: removed nodes come back.

More words, deeper paths

Twenty words to build with, from cab and cat to carriage and topology, and ten prefixes to search.

Theory and complexity

The root, shared prefixes, the end-of-word flag and the cost of every operation, illustrated.

Python, Java and C++

A trie implementation with insert, search, delete and startsWith, explained part by part.

Quiz

Check what you have learned before moving on.

Grow a trie
letter by letter.

Download VisiGrab and step through every insertion, deletion and prefix search yourself.

The trie is one of 30+ topics. See them all