
Problem
Solution
Submissions
Prefix Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to implement a Trie (Prefix Tree) data structure. A trie is a tree-like data structure that stores a dynamic set of strings, where the keys are usually strings. Your Trie should support inserting strings, searching for complete words, and checking if any word starts with a given prefix.
Example 1
- Input: Operations = ["insert", "search", "search", "startsWith", "insert", "search"], Values = ["apple", "apple", "app", "app", "app", "app"]
- Output: [null, true, false, true, null, true]
- Explanation:
- Insert "apple" into the trie.
- Search for "apple" - returns true as it exists.
- Search for "app" - returns false as complete word doesn't exist.
- Check if any word starts with "app" - returns true. Insert "app" into the trie.
- Search for "app" - now returns true as complete word exists.
- Insert "apple" into the trie.
Example 2
- Input: Operations = ["insert", "insert", "search", "search", "startsWith"], Values = ["hello", "help", "hell", "hello", "hel"]
- Output: [null, null, false, true, true]
- Explanation:
- Insert "hello" into the trie.
- Insert "help" into the trie.
- Search for "hell" - returns false as complete word doesn't exist.
- Search for "hello" - returns true as it exists.
- Check if any word starts with "hel" - returns true.
- Insert "hello" into the trie.
Constraints
- 1 ≤ word.length, prefix.length ≤ 2000
- word and prefix consist only of lowercase English letters
- At most 3 * 10^4 calls in total will be made to insert, search, and startsWith
- Time Complexity: O(m) for each operation where m is the length of the word
- Space Complexity: O(ALPHABET_SIZE * N * M) where N is number of words and M is average length
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
- Create a TrieNode class with an array to store children and a boolean flag for end of word
- Use an object or Map to represent children nodes for each character
- For insertion, traverse the trie creating new nodes as needed and mark the end
- For search, traverse the trie and check if the end node is marked as end of word
- For prefix search, traverse the trie and return true if you can complete the prefix path