Browse Curriculum
FAANGPrep Sprint
Medium
Implement Trie (Prefix Tree)
Design a data structure that supports insert, search, and startsWith.
Problem Description
Implement Trie class:
insert(word): Inserts stringword.search(word): Returns true if stringwordis in the trie.startsWith(prefix): Returns true if there is a previously inserted string havingprefix.
Interactive Visualization
Step 1 / 1
Visualization coming soon...
Initializing...
1x
Watch how insert creates new nodes only when necessary, and search traverses existing paths.
Algorithm Strategy
- Node Structure: Each node contains a map/array of size 26 (for 'a'-'z') and a boolean
isEnd. - Insert: Traverse down; create nodes if missing. Mark last node as
isEnd. - Search: Traverse down; if node missing -> return false. At end, return
node.isEnd. - StartsWith: Traverse down; if node missing -> return false. If loop finishes, return true.
Dry Run: Insert 'cat'
| Char | Node Exists? | Action |
|---|---|---|
| 'c' | No | Create 'c' node. Move to 'c'. |
| 'a' | No | Create 'a' node. Move to 'a'. |
| 't' | No | Create 't' node. Move to 't'. |
| End | - | Mark 't' node as isEnd=True. |
Solution
O(L) Time per operation where L is word length.
1class TrieNode:2 def __init__(self):3 self.children = {}4 self.is_end = False56class Trie:7 def __init__(self):8 self.root = TrieNode()910 def insert(self, word: str) -> None:11 node = self.root12 for char in word:13 if char not in node.children:14 node.children[char] = TrieNode()15 node = node.children[char]16 node.is_end = True1718 def search(self, word: str) -> bool:19 node = self.root20 for char in word:21 if char not in node.children:22 return False23 node = node.children[char]24 return node.is_end2526 def startsWith(self, prefix: str) -> bool:27 node = self.root28 for char in prefix:29 if char not in node.children:30 return False31 node = node.children[char]32 return True
Edge Cases & Common Mistakes
Check for:
Word is Prefix: Searching for 'app' when 'apple' exists. Should return False (unless 'app' was inserted independently).
Prefix Search: startsWith('app') should return True if 'apple' exists.
Duplication: Inserting 'app' twice shouldn't break anything.
Complexity Analysis
- Time Complexity: O(L) for Insert/Search/StartsWith.
- Space Complexity: O(N * L) total characters stored.
ON THIS PAGE
- Problem Description
- Interactive Visualization
- Algorithm Strategy
- Dry Run: Insert 'cat'
- Solution
- Edge Cases & Common Mistakes
- Complexity Analysis
