208. Implement Trie (Prefix Tree) - Detailed Explanation
Problem Statement
Implement the Trie class:
Trie()Initializes the trie object.void insert(String word)Inserts the stringwordinto the trie.boolean search(String word)Returnstrueif the exact stringwordis in the trie (i.e., was previously inserted), orfalseotherwise.boolean startsWith(String prefix)Returnstrueif there is any previously inserted string that starts with the givenprefix, orfalseotherwise.
Examples
Input
["Trie","insert","search","search","startsWith","insert","search"]
[[], ["apple"],["apple"],["app"], ["app"], ["app"],["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false (only prefix "app" exists)
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Constraints
1 ≤ word.length, prefix.length ≤ 2000wordandprefixconsist only of lowercase English letters.- At most 3·10⁴ calls in total will be made to
insert,search, andstartsWith.
Approach
Trie Node Structure
Each node holds:
- An array (or map) of up to 26 child pointers, one for each lowercase letter.
- A boolean flag
isEndindicating whether a word ends at this node.
Operations
insert(word)
- Start at the root node.
- For each character
cinword:- Compute its index
i = c - 'a'. - If
node.children[i]isnull, create a newTrieNode. - Move
node = node.children[i].
- Compute its index
- After the last character, mark
node.isEnd = true.
search(word)
- Traverse exactly as in
insert, but if at any stepnode.children[i]isnull, returnfalse. - After processing all chars, return
node.isEnd.
startsWith(prefix)
- Traverse as in
search, but do not checkisEnd. - If you complete the traversal without hitting
null, returntrue.
Complexity Analysis
- Time: O(m) per operation (m = length of word or prefix).
- Space: In the worst case, O(N·L) for storing all inserted words (N words of average length L), since each character may create a new node.
Python Code
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
Common Mistakes
- Forgetting to mark
isEndon insert, causingsearchto return false for inserted words. - Using a map per node instead of a fixed‑size array, which increases constant factors.
- In
startsWith, accidentally requiringisEndto be true.
Edge Cases
- Inserting or searching the same word multiple times.
- Searching for a prefix that is exactly an inserted word.
- Very long words near the maximum length.
Related Problems
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
3105. Longest Strictly Increasing or Strictly Decreasing Subarray - Detailed Explanation
Learn to solve Leetcode 3105. Longest Strictly Increasing or Strictly Decreasing Subarray with multiple approaches.
1760. Minimum Limit of Balls in a Bag - Detailed Explanation
Learn to solve Leetcode 1760. Minimum Limit of Balls in a Bag with multiple approaches.
766. Toeplitz Matrix - Detailed Explanation
Learn to solve Leetcode 766. Toeplitz Matrix with multiple approaches.
1091. Shortest Path in Binary Matrix - Detailed Explanation
Learn to solve Leetcode 1091. Shortest Path in Binary Matrix with multiple approaches.
2965. Find Missing and Repeated Values - Detailed Explanation
Learn to solve Leetcode 2965. Find Missing and Repeated Values with multiple approaches.
76. Minimum Window Substring - Detailed Explanation
Learn to solve Leetcode 76. Minimum Window Substring with multiple approaches.
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
$197

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
$78
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
$78
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.