DSA Notes
Master trie data structures for autocomplete and prefix-based searching.
What is a Trie?
A Trie (pronounced "try") is a tree-like data structure designed specifically for storing and searching strings efficiently. Unlike a binary search tree that stores complete keys in each node, a trie stores one character per node, with the path from root to any node representing a prefix of the stored strings.
The name comes from "retrieval" — because tries make string retrieval extremely fast. If you have ever used autocomplete on Google, phone keyboards, or IDE code completion, you have used functionality powered by trie-like structures.
Key insight: A trie lets you search for any word in O(m) time where m is the word length — completely independent of how many words are stored. Whether your dictionary has 100 words or 10 million words, looking up a 5-letter word always takes exactly 5 steps.
Implementation in Python
Java Implementation
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
| Insert | O(m) | O(m) per word worst case |
| Search | O(m) | O(1) |
| Prefix search | O(m) | O(1) |
| Delete | O(m) | O(1) |
| Autocomplete | O(m + k) | O(k) for results |
| Total space | - | O(n × m × alphabet_size) worst case |
Where m = word length, n = number of words, k = number of matches.
Trie vs Other Data Structures
| Feature | Trie | HashMap | BST |
|---|---|---|---|
| Exact search | O(m) | O(m) avg | O(m log n) |
| Prefix search | O(m) | O(n×m) | O(m log n) |
| Autocomplete | O(m + k) | O(n×m) | O(m log n + k) |
| Sorted iteration | Natural | Not possible | Natural |
| Space | Can be large | Compact | Moderate |
| Best for | Prefix operations | Exact lookups | Ordered data |
Real-World Applications
- Autocomplete systems — Google search, IDE code completion, phone keyboards
- Spell checkers — finding close matches for misspelled words
- IP routing — longest prefix matching in router tables
- Phone directories — T9 predictive text, contact search
- Genome analysis — searching for DNA/RNA sequence patterns
- Word games — Scrabble solvers, Boggle finders, crossword helpers
Variations
Compressed Trie (Patricia/Radix Tree): Merges chains of single-child nodes into one edge. Reduces space significantly for sparse datasets.
Ternary Search Tree: Each node has three children (less than, equal to, greater than). Uses less space than standard tries while maintaining good performance.
Suffix Trie/Tree: Stores all suffixes of a string. Used for advanced string matching problems.
Interview Questions
Q1: What is the time complexity of searching in a trie vs a hash map? A: Both are O(m) for exact search where m is key length. But tries excel at prefix operations — finding all words with a given prefix is O(m + k) vs O(n×m) for hash maps scanning all entries.
Q2: How would you implement autocomplete using a trie? A: Navigate to the node representing the prefix (O(m)). Then perform DFS/BFS from that node to collect all complete words below it. Optionally sort by frequency or recency for better suggestions.
Q3: How do you handle memory issues with tries? A: Use compressed tries (merge single-child chains), use arrays only for the alphabet subset actually used, or use hash maps instead of arrays for children (trading some speed for space).
Q4: What is the difference between a trie and a suffix tree? A: A regular trie stores a set of words. A suffix tree stores all suffixes of a single string, enabling substring matching in O(m) time. Suffix trees are specialized for within-string pattern matching.
Q5: How would you find the longest common prefix of all words in a trie? A: Start from root, follow the path as long as each node has exactly one child and is not end-of-word. The path length is the longest common prefix. Time: O(m) where m is the LCP length.
Key Takeaways
- Tries provide O(m) operations independent of dataset size — perfect for dictionaries and autocomplete
- The prefix-sharing property makes tries memory-efficient for words with common prefixes
- Every coding interview involving string prefixes likely needs a trie
- In practice, compressed tries and ternary search trees offer better space-time trade-offs
- Learn the basic insert/search/startsWith operations — they appear directly in LeetCode problems
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Trie - Prefix Tree for Efficient Searching.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, advanced, topics, trie
Related Data Structures & Algorithms Topics