Chapter 13 ยท Advanced Data Structures

Trie (Prefix Tree)

Words that share a beginning share a path. Insert, search, count a prefix and autocomplete in time proportional to the word's length, no matter how many words are stored.

Stored words (click one to put it in the box):
walked (one hash-map lookup per letter) node created / removed found / suggestion current node end of a word (isEnd) missing child
Autocomplete suggestions
Run "Prefix count + autocomplete".

How to read this

Try this

  1. Build the default list car, card, care, cat, dog, dot. You should get 11 nodes (10 letters + the root) for 20 characters, so sharing saves 10 letter nodes.
  2. Search ca: every letter is found, yet the answer is false because the node for "a" has no green ring. Then run prefix count on ca: 4 words (car, card, care, cat).
  3. Search cow: the walk stops at the dashed "o" under "c" after 2 steps. A miss can be even cheaper than a hit.
  4. Delete card: only the "d" node disappears. Then delete car: no node disappears, only the green ring on "r" (because "care" still uses it).
  5. Add words with no shared beginnings (zebra, quilt, juice). Watch the node count approach the character count: a trie saves space only when prefixes are shared.

Go deeper