Browse Curriculum
Trie
Medium
Implement Trie (Prefix Tree)
Design a data structure that supports insert, search, and startsWith.
10 min read
Solve on LeetCodeProblem 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.
ON THIS PAGE
- Problem Description
- Interactive Visualization
- Algorithm Strategy
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
