Tries

Difficulty
Importance

The problem

Searching for all words with a given prefix, or checking whether any stored string starts with a given sequence, is awkward and slow with a hash table — a hash table can only tell you if an exact string exists, not efficiently enumerate everything sharing a prefix.

Why now

Trees already gave the general branching structure; hash tables already gave fast exact-match lookup for strings. A trie is what you get by organizing strings char-by-char down a tree instead of hashing them whole — trading hash tables' O(1) exact lookup for prefix-query power a hash table structurally cannot offer.

Mental model

A trie is a tree where each edge is labeled with one character, and a path from the root spells out a string — every node along a stored word's path is shared with every other word starting the same way, so a prefix search is just walking down to that point in the tree once, not scanning every stored string.

Requires

Used in

Projects

  • Implement a trie supporting insert, exact search, and prefix search (startsWith) from scratch
  • Build an autocomplete feature backed by a trie that returns all stored words matching a given prefix

Examples

  • Searching for all words starting with 'pre' in a trie is a single walk down 3 edges, then a traversal of everything below that node — no scanning of unrelated words
  • cat and car share the same first two trie nodes (c, a), diverging only at the third character — the shared prefix is stored exactly once

Resources

Mastery checklist