Pattern

Trie (prefix tree)

Store strings by their shared prefixes in a tree, so lookup, prefix-check, and multi-pattern search all cost proportional to string length, not collection size.

What it is

A trie is a tree where each edge represents one character and each root-to-node path spells out a prefix. Words that share a prefix share the nodes for that prefix, so the structure encodes an entire dictionary's common structure once instead of once per word. Every operation — insert, exact lookup, "does any word start with this" — is a walk from the root, one character at a time, so its cost depends only on the length of the string being processed, never on how many words are stored. The one detail every implementation needs is a per-node flag (or stored value) marking "a complete word ends here," because a node being reachable is not the same as a word ending there.

When it applies

Tells in the problem

The classic mistake

The most common bug is forgetting the terminal flag entirely, or checking only "did the walk reach a node" instead of "did the walk reach a node marked as a complete word" — this makes search("app") incorrectly return true after only "apple" has been inserted, because the path exists even though no word ends exactly there. A second common mistake shows up in multi-word search over a grid or board: running a fresh single-word search once per target word, which throws away the fact that many target words share prefixes and forces the same cells to be explored repeatedly. The fix in both cases is the same instinct — treat "the path exists" and "a word ends here" as two separate questions the trie must answer, and let one shared trie serve every query instead of rebuilding structure per query.

Questions to start with

All 5 trie (prefix tree) questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.