Home
DSA Visualizer
Advanced Topics
Introduction to Tries
Introduction to Tries
A preliminary look at why Prefix Trees (Tries) are superior to Hash Maps for certain string operations.
PREFIX "APP"
FOLLOW EDGE
→
→
→
LIST READS
0
TRIE STEPS
0
The list, filtered
Looking for words starting with "APP". The list holds 5; the trie holds one path per distinct prefix.
Next
Character 'A': the list re-reads all 5 surviving words — 5 character reads so far. The trie follows one edge: 1 step, whatever the corpus size.
Intuition
If you want to search for the word "Apple" in a dictionary, you don't read every single word. you go to the 'A' section, then 'Ap', then 'App'...
A Trie mimics this process. It structures data by prefix, allowing us to traverse character by character, efficiently ignoring irrelevant branches.
Concept
Trie vs List:
- List Search: Checks every word. O(N * L).
- Trie Search: Follows a single path. O(L).
Tries are essentially N-ary trees where each edge represents a character.
How it Works
The visualizer simply compares:
- Linear Scan: A red highlight checking every word "Apple" vs "Banana", "Apple" vs "Apricot"...
- Prefix Traversal: A green path moving 'A' -> 'P' -> 'P'. It's much faster.
Step-by-Step Breakdown
1. Start at Root node.
2. For each character in the target string:
3. Check if a child node exists for that character.
4. If yes, move to it. If not, stop (not found).
When to Use
- When you need prefix-based lookups.
- Sorting strings (Radix Sort uses Trie logic).
When NOT to Use
- If you only need exact match checks: a hash set is simpler. It is still O(L) per lookup, because hashing a string reads every character, so its advantage is simplicity and constant factors, not complexity.
How to Identify
"Starts with prefix...", "Autocomplete", "Spell check".
