Trie (Prefix Tree) — Autocomplete Explained — Complete Beginner Guide
Learning Objectives
- Model words as paths in a trie
- Implement insert, search, and prefix check
- Explain why autocomplete stays fast
- Measure time against string length m
- Spot when tries cost too much memory
What Is a Trie?
A trie, short for prefix tree, stores words character by character. Each node holds a character and links to children for the next characters. A shared path means a shared prefix.
The root is empty. Following edges spells the word. Marking the end of a word distinguishes cat from caption.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def search(self, word):
node = self._walk(word)
return node is not None and node.is_end
def starts_with(self, prefix):
return self._walk(prefix) is not None
def _walk(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return None
node = node.children[ch]
return node
trie = Trie()
for word in ["car", "card", "care", "dog"]:
trie.insert(word)
print(trie.search("car")) # True
print(trie.search("ca")) # False
print(trie.starts_with("car")) # True
Autocomplete Explained
Given a partial query, walk the trie to the prefix node, then collect words under that subtree.
def autocomplete(trie, prefix, limit=10):
node = trie._walk(prefix)
if node is None:
return []
found = []
def dfs(current, path):
if len(found) >= limit:
return
if current.is_end:
found.append(prefix + path)
for ch, child in current.children.items():
dfs(child, path + ch)
dfs(node, "")
return found
print(autocomplete(trie, "car"))
# car, card, care
A hash table of full words can check exact matches fast, but prefix enumeration would require scanning every key. The trie stores prefix structure explicitly.
Complexity Table
Let m be word or prefix length.
| Operation | Trie | Hash Table | Sorted Array |
|---|---|---|---|
| Insert | O(m) | O(m) average | O(n) shift or O(n log n) rebuild |
| Exact search | O(m) | O(m) average | O(m log n) with binary search style |
| Prefix search | O(m) plus results | O(total keys scan) | O(m log n) plus range |
| All completions | Proportional to subtree | Scan whole table | Scan range |
Node Design Choices
| Child Storage | Lookup Cost | Memory |
|---|---|---|
| Hash map per node | Average O(1) | Higher overhead |
| Sorted array of children | O of alphabet size with search | Compact |
| Fixed array for full alphabet | O(1) | Wastes space for sparse sets |
Python dictionaries give a clean balance for learning code.
Real-World Uses
- Search box autocomplete
- Spell checkers and typo suggestions
- IP routing prefix tables
- Word games such as Boggle lookups
- Predictive text on phones
- Longest common prefix across a word list
Space Cost
Tries can duplicate large common structures in other designs, but each distinct character edge exists once along its path. Still, per-node dictionary overhead adds up. Compressed tries merge single-child chains to save space.
| Concern | Note |
|---|---|
| Memory per node | Child dict plus flag |
| Deep alphabets | Long words grow tall tries |
| Fix | Radix or compressed tries |
Trie versus Balanced BST
| Task | Trie | Balanced BST |
|---|---|---|
| Prefix enumeration | Natural | Requires range tricks |
| Exact lookup | O(m) | O of m times log n comparisons |
| Sorted output | Alphabet walk | Inorder traversal |
| Extra fields | Easy metadata on nodes | Harder on plain keys |
Trie Trade-Off Notes
Decide child storage from your alphabet and scale. A dictionary per node is flexible and fast for mixed character sets. A fixed array of size twenty-six is tight for English lowercase only but wasteful for unicode. A sorted child array saves memory when degrees are small but needs binary search per step.
# Count nodes roughly equals total characters when prefixes do not fully collapse
def approx_nodes(words):
return sum(len(w) for w in words)
print(approx_nodes(["car", "card"]))
Tries shine for prefix workloads and fall behind hash tables when you only need exact match on short keys. Memory grows with distinct character edges, so compress long single-child chains into radix trees in production systems.
If autocomplete results need ranking, store extra metadata at end nodes such as frequency, then collect and sort candidates under the prefix node. The structure stays the same while the payload grows to fit the product requirement.
Key Takeaways
💡
- A trie shares common prefixes as common paths
- Insert and search cost O of word length m, not dictionary size
- Autocomplete is a subtree walk from the prefix node
- Hash tables match exact lookups but weaken prefix queries
- Tries trade memory overhead for excellent prefix behavior
Practice Questions
- Insert apple, app, and apt then sketch the shared structure near the root.
- Why does prefix search beat a hash table even though both are fast?
- Estimate trie space for ten thousand words of average length ten using dictionary children.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions