
Problem
Solution
Submissions
Prefix Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C 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. Implement the Trie class with insert, search, and startsWith operations.
Example 1
- Input:
Operations: ["insert", "search", "search", "startsWith", "insert", "search"]
Arguments: [["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] - Output: [null, true, false, true, null, true]
- Explanation:
- Insert "apple" into the trie. Search for "apple" - returns true (word exists).
- Search for "app" - returns false (prefix exists but not as complete word).
- Check if any word starts with "app" - returns true.
- Insert "app" as a complete word. Search for "app" - returns true (now exists as complete word).
- Insert "apple" into the trie. Search for "apple" - returns true (word exists).
Example 2
- Input:
Operations: ["insert", "insert", "search", "search", "startsWith"]
Arguments: [["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 (prefix exists but not complete word).
- Search for "hello" - returns true (complete word exists).
- Check if any word starts with "hel" - returns true.
- Insert "hello" into the trie. Insert "help" 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 will be made to insert, search, and startsWith
- Time Complexity: O(m) for all operations where m is key length
- Space Complexity: O(ALPHABET_SIZE * N * M) where N is number of keys 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 structure with children array and isEndOfWord flag.
- Use an array of size 26 for each node to store child pointers (a-z).
- For insert: traverse the trie creating nodes as needed, mark last node as end of word.
- For search: traverse the trie following the word path, check if last node is end of word.
- For startsWith: traverse the trie following the prefix path, return true if path exists.
- Use character arithmetic (ch - 'a') to get array index for each character.