-
Notifications
You must be signed in to change notification settings - Fork 0
Trie
krishanthan4 edited this page Dec 16, 2025
·
1 revision
Implement a Trie (also called Prefix Tree) data structure for efficient string storage and retrieval, particularly useful for prefix-based operations.
A trie is a tree-like data structure used to store strings where each node represents a character. Words with common prefixes share the same path from the root, making it efficient for prefix operations.
-
Time Complexity:
- Insert: O(m) where m is the length of the word
- Search: O(m)
- StartsWith: O(m)
- Delete: O(m)
- Space Complexity: O(ALPHABET_SIZE * N * M) where N is number of words and M is average length
- Best for: Prefix operations, autocomplete, spell checking
Each TrieNode contains:
- Map of character to child TrieNode
- Boolean flag indicating end of word
Trie with "cat", "car", "dog":
root
/ \
c d
| |
a o
/ \ |
t r g
* * *
(* = end of word)
- insert(word): Add a word to the trie
- search(word): Check if exact word exists
- startsWith(prefix): Check if any word starts with prefix
- delete(word): Remove a word from trie
- wordsWithPrefix(prefix): Get all words with given prefix
Implement the following methods in Trie.java:
-
insert(String word)- Insert a word -
search(String word)- Search for exact match -
startsWith(String prefix)- Check for prefix -
delete(String word)- Delete a word -
wordsWithPrefix(String prefix)- Find all words with prefix
- Insert and search words
- Search for non-existent words
- Check prefixes
- Words that are prefixes of other words ("app" and "apple")
- Empty string
- Delete words
- Single character words
- Words with common prefixes
- Use a HashMap<Character, TrieNode> for children
- Mark end of word with a boolean flag
- For search: traverse to end and check isEndOfWord
- For startsWith: just check if path exists
- For delete: use recursion and clean up nodes with no children
1. Start at root
2. For each character in word:
- If child doesn't exist, create it
- Move to child
3. Mark last node as end of word
1. Start at root
2. For each character in word:
- If child doesn't exist, return false
- Move to child
3. Check if current node is marked as end of word
- Autocomplete systems
- Spell checkers
- IP routing (longest prefix matching)
- T9 predictive text
- Solving word games (Boggle, Scrabble)
- Dictionary implementation
- Search engines
- Can quickly find all words with given prefix
- Alphabetical ordering of words
- No hash collisions
- Predictable lookup time
- More memory intensive
- Cache-unfriendly (pointer chasing)
- More complex to implement
- How would you implement word count (number of times a word is inserted)?
- How would you find the longest word in the trie?
- How would you implement a case-insensitive trie?
- Can you optimize space by compressing common paths?
- Radix Tree (Patricia Trie): Compressed trie
- Suffix Tree: For substring operations
- Ternary Search Tree: Space-efficient variant
- Compressed Trie: Merge nodes with single child
- Not marking end of word correctly
- Forgetting to handle words that are prefixes of others
- Memory leaks in delete operation
- Not handling empty string
- Case sensitivity issues
When deleting:
- Check if word exists
- Remove end-of-word marker
- Clean up nodes with no children (optional optimization)
- Don't delete nodes that are part of other words
| Operation | Trie | BST |
|---|---|---|
| Search | O(m) | O(log n) |
| Insert | O(m) | O(log n) |
| Space | Higher | Lower |
| Use Case | Prefix ops | General |
m = word length, n = number of words
- Implement autocomplete
- Word search in 2D grid
- Replace words (longest prefix)
- Design search autocomplete system
- Longest word in dictionary
- Stream of characters
- Hash Table
- Binary Search Tree
- Suffix Tree
- Radix Tree