Trie#
A trie (prefix tree) stores strings character-by-character. Each path from root to a marked node spells one stored word. Tries excel at prefix queries, autocomplete, and shared-prefix compression.
When to use a trie#
| Scenario | Why trie |
|---|---|
Prefix search (“all keys starting with pre”) |
Natural O(L) walk |
| Autocomplete / dictionary | Branch per character |
| Word search on grid | Trie + backtracking |
| XOR maximum of binary strings | Bitwise trie variant |
| Spell checker / IP routing (conceptually) | Longest prefix match |
Prefer dict / set when you only need exact word lookup, not prefix structure.
Complexity#
Let L = word length, N = number of words stored, A = alphabet size (26 for lowercase letters).
| Operation | Time | Space |
|---|---|---|
| Insert word | O(L) | O(L) new nodes worst case |
| Exact search | O(L) | O(1) extra |
Prefix search (startsWith) |
O(L) | O(1) extra |
| Delete word | O(L) | O(1) extra |
| Store N words total | — | O(total characters) ≤ O(N · L) |
Compared to hash table: trie uses more space for sparse prefixes but wins on prefix and lexicographic ordering operations.
Structure#
Each node holds:
- children — map char → child node
- is_end_of_word — whether a word ends here
Implementation#
Insert/search/prefix: O(L) time, O(1) auxiliary space per call.
Delete: O(L) time; may prune unused nodes.
Array vs map children#
| Child storage | Pros | Cons |
|---|---|---|
dict[str, TrieNode] |
Sparse alphabet, flexible | Pointer overhead |
| Fixed array size 26 | Fast index ord(c) - ord('a') |
Wastes space if sparse |
Use dict in Python interviews unless problem fixes alphabet to lowercase a–z.
Trie vs hash set#
| Trie | set of strings |
|
|---|---|---|
| Exact lookup | O(L) | O(L) hash |
| Prefix queries | O(L) | O(N) scan all strings |
| Space | Shared prefixes | Each string stored fully |
| Lexicographic iterate | DFS order | Sort required |
Common patterns#
- Store reversed words — palindrome pairing problems.
- Bit trie — each node has
0and1child; used for maximum XOR subarray. - Trie + DFS on grid — prune when prefix not in trie.