Tries: one node per prefix

Video lessonComing soon

1 A keyboard that finishes words

A phone keyboard suggests words while we type. After "ca", it offers car, cart, care and cat.

A hash set of words answers "is car a word?" in about one step. But a hash only knows whole words. To answer "which words start with ca?", the set has to check every word. With 10⁵ words and 10⁵ such questions, that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).

The words themselves show the way out. Car, cart, care and cat all start with "ca". We can store that start once and keep every word that begins with it below. Then the keyboard only has to find "ca" and look underneath.

2 One node per prefix

A trie (said "try") stores words that way. It is a tree, as in the tree lessons, but a node can have up to 26 children, one for each letter. Each node stands for one prefix: the first few letters of a word. The root is the empty prefix. Each edge adds one letter, so the path from the root to a node spells its prefix.

Here is the trie of car, cat, cart, care and dog:

car"car"t"cart"e"care"t"cat"dog"dog"
Five words. A ringed node is where a word ends

Words that start the same share a path. The five words have 17 letters, but the trie has only 9 nodes below the root. Typing on the keyboard is a walk down this tree: each key moves one node down.

The path alone cannot tell a word from a prefix. "car" is a word and "ca" is not, but both are nodes on the way to "cart". So each node keeps one more field, the end flag. It is true when a word ends exactly at that node, and the drawing rings those nodes.

In code, a node holds 26 child slots and the flag. The slot for a letter c is at index c - 'a', so a is slot 0 and z is slot 25. An empty slot means no word continues with that letter:

abcdefghijklmnopq→rs→tuvwxyz
The slots of node ca: only r and t lead anywhere

3 Insert: walk, and make what is missing

To insert a word, we start at the root and follow its letters. For each letter, we move to the child for that letter, and make that child first if it is missing. After the last letter, we set the end flag on the node we stand on.

Here are the five words going in, one at a time. The blue path is the word just inserted:

Inserting five words
car"car"
Step 1: car makes three new nodes

Step 4, inserting care, shows both cases:

LetterChild there?What insert doesNode after
cyesmove downc
ayesmove downca
ryesmove downcar
enomake it, move downcare
endset the end flagcare, ringed

Only e is new. The first three nodes were built by the words before it.

5 Cost, and array against map

Each method moves one node per letter. So insert, search and startsWith take O(L) time for a word of length L, however many words the trie holds. Back on the keyboard, 10⁵ questions of about 10 letters each take around 10⁶ steps instead of 10¹⁰.

Memory is the price. Every node carries 26 slots, used or not. Take 10⁵ words of 10 letters each:

  • Nodes. At most one per letter, so 10⁶ nodes. Shared prefixes only lower this.
  • Slots. 26 per node, so 2.6 × 10⁷.
  • Bytes. At 8 bytes a pointer, about 200 MB.

Random words share little beyond their first few letters, so a test can come close to this. In general, the space is O(N × 26) for N letters inserted.

A map in each node stores only the children that exist:

Array of 26Map
Find a childone indexone hash lookup, slower
Memory26 slots per node, mostly emptyone entry per real child
Lettersa small, known setany characters

For lowercase letters, the array is the usual choice. A map fits when the alphabet is large or unknown, or when 26 slots per node would not fit in memory.

6 Counts, deletes and wildcards

The keyboard could also show how many words start with what we typed. For that, each node keeps a prefix count: how many inserted words pass through it. Insert adds 1 at every node it walks through, so the count for "ca" is one walk and one read.

PrefixWords through itCount
cacar, cat, cart, care4
carcar, cart, care3
catcat1
dodog1

A second count in place of the end flag says how many times the word itself was inserted. "Implement Trie II (Prefix Tree)" asks for both counts.

Two more operations build on the same walk:

  • Deleting a word. Clearing the end flag is not enough. After deleting dog, the nodes d and o remain, and startsWith("do") still says true. Either remove the nodes no other word uses, going back up from the end, or take 1 from the prefix count along the path and treat a node with count 0 as missing.
  • A wildcard letter. In "Design Add and Search Words Data Structure", a . matches any letter. At a ., the walk tries every child, and the search is true if any branch ends on a ring. This is a depth-first search, written with recursion. For "ca.", it tries r and t, and car is ringed.

7 Mistakes and edge cases

  • No end flag. Without it, search returns true for any prefix. After inserting car, search("ca") comes out true instead of false.
  • Setting the flag only on a new node. Insert cart, then car. Inserting car makes no node, so its flag is never set, and search("car") returns false.
  • A search that makes nodes. Copying insert's loop into search makes a node for every missing letter. After search("cab") returns false, startsWith("cab") returns true.
  • Assuming lowercase letters. c - 'a' is a slot from 0 to 25 only for a to z. An uppercase C gives −30, outside the array, which is a Runtime Error. Read the constraints for the alphabet, and use 128 slots or a map for anything wider.
  • Treating the empty prefix as a miss. Every word starts with the empty prefix, so startsWith("") is true. The loop already returns the root for it. An extra if that returns false breaks it.

8 When to use a trie

The sign is many words and questions about how they start, or a walk that matches words one letter at a time.

  • Prefix questions over many words. Autocomplete, or counting words that start with something. Build the trie once, then each question is one walk.
  • Words built one letter at a time. A word can be built that way exactly when every node on its path is ringed. "Longest Word in Dictionary" and "Longest Word With All Prefixes" check this.
  • Matching many words during one walk. In "Word Search II", the walk over the grid moves down the trie at each cell. It stops as soon as no word starts with the letters so far.
  • All substrings of one string. Every substring is a prefix of some suffix, so a trie of the suffixes holds every substring.
  • Not for whole words alone. When every question is "is this exact word there?", a hash set is simpler.

The next lesson stores numbers in a trie, one bit per level, to find the pair with the largest XOR.

When a problem asks how words start, or walks letters one at a time, draw the trie of its words before writing code.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.