š² Trie Algorithms
Master prefix trees (tries) for efficient string search, autocomplete, and prefix matching operations.
Overview
What is a Trie?
Key Trie Algorithms
Trie Insert & Search
Insert words into trie and search for exact matches
Prefix Search & Autocomplete
Find all words with given prefix
Word Break (Trie)
Check if string can be segmented into dictionary words
Maximum XOR Pair
Find two numbers with maximum XOR using trie
Interactive Visualizer
Trie Visualization
Trie Insert & Search Trie Visualizer
Watch how words are inserted, searched, and how common prefixes share nodes in the trie.
Deep Dive: Trie Insert & Search
Time Complexity
Time: O(L)Space Complexity
Space: O(N*L)Best For
Prefix OperationsTrie Strategy
python
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 char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_endDefine Node
Each node has children (dictionary/hash map) and an end-of-word flag.
Insert
Traverse character by character, creating missing nodes. Mark last node as end.
Search
Traverse characters. Return false if any character missing. Return is_end at final node.
Prefix Query
Navigate to prefix node, then collect all words in its subtree via DFS.
Real-World Applications
Autocomplete
Search engines, IDE code completion, text prediction
Spell Checkers
Dictionary lookup with suggestions for misspelled words
IP Routing
Longest prefix matching in network routers
Search Engines
Inverted index, prefix-based query suggestions
Phone Directory
Contact search by name prefix
Bioinformatics
Gene sequence pattern matching
Interview Questions
When would you use trie over hash table?
Trie excels when: 1) Prefix search is needed (autocomplete), 2) Words share common prefixes (memory efficient), 3) Lexicographic ordering is needed, 4) You need longest prefix matching (routing). Hash table can't do prefix search efficiently.
What are the memory tradeoffs of trie?
Trie can use more memory than hash table for non-overlapping words (each node is an object). But for words with shared prefixes (like 'test', 'testing', 'tested'), trie is more memory efficient. Compressed trie (radix tree) reduces memory.
How would you implement autocomplete with trie?
Insert all dictionary words. For a prefix, navigate to prefix node, then perform DFS to collect all words under that node. Sort by frequency/rank. Can optimize with top-k suggestions per node.
Knowledge Check
1. What is the time complexity of trie search?
2. What does each node in a trie store?
3. What is the main advantage of trie over hash set?
4. Space complexity of a trie with N words of avg length L?
5. Which problem is best solved with trie?