Tries
Prefix trees that share common beginnings between words.
- visited / done
- active this step
- read by this step
- result
Insert “cat”
Creates nodes for c, a and t, and marks t as the end of a word.
VARIABLES
- word
- "cat"
- root branches
- c
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A trie stores strings one character per level. Each node maps a character to a child node, and a flag marks where a word ends.
Why it matters
Prefix lookups take O(L) for a word of length L, however many words are stored.
Think of it like this
A phone’s autocomplete: typing “ca” narrows to every word under that branch.
Use it when
- Prefix search and autocomplete
- Searching many words against a board or text
- Longest common prefix questions
Avoid it when
- Exact lookups only - a hash set is simpler
- Very few words - the node overhead isn’t worth it
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Insert a word of length L | O(L) | O(L) new nodes |
| Search or startsWith | O(L) | O(1) |
| Build from many words | O(total characters) | O(total characters) |
Often confused with: hash sets - they answer “is this word present?” but not “which words start with this?”
How to recognize it
Clues in interview prompts that point straight to this pattern.
- “Implement insert, search and startsWith” is the classic trie prompt
- Many words in a grid: build a trie once, then run DFS
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Forgetting the end-of-word marker - “ca” would look like a word
- Confusing search (needs the marker) with startsWith (doesn’t)
- Creating nodes while searching
Edge cases to test
- An empty string as a word or prefix
- One word that is a prefix of another (“car”, “card”)
- A prefix longer than any stored word
Knowledge check
Quick check to lock in the intuition.
After inserting only “card”, what does search("car") return?
Practice
Apply what you just watched on real interview problems.