
Problem
Solution
Submissions
Trie (Prefix Tree) Data Structure
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 15
Write a program to implement a Trie (Prefix Tree) data structure for efficient word storage and retrieval.
Example 1
- Input:
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] - Output:
[null, null, true, false, true, null, true] - Explanation:
- Insert "apple", search returns true.
- Search "app" returns false.
- startsWith("app") is true.
- Insert "app", now search returns true.
Example 2
- Input:
["Trie", "insert", "insert", "search", "startsWith", "search"]
[[], ["hello"], ["world"], ["world"], ["worl"], ["wor"]] - Output:
[null, null, null, true, true, false] - Explanation:
- Insert "hello" and "world".
- search("world") returns true.
- startsWith("worl") true, search("wor") false.
Constraints
- 1 ≤ word.length, prefix.length ≤ 2000
- Only lowercase English letters allowed
- At most 3 * 10^4 calls to insert/search/startsWith
- Time Complexity: O(m)
- Space Complexity: O(n * m)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a tree-like data structure where each node represents a single character
- Each node should contain links to child nodes, one for each possible character
- Mark nodes that represent the end of a word
- For startsWith(), you only need to check if the prefix path exists
- For search(), check if the path exists AND if the last node is marked as the end of a word