
Problem
Solution
Submissions
Implement Trie (Prefix Tree)
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 12
Write a C# program to implement a Trie (Prefix Tree). A trie is a tree-like data structure used to store a dynamic set of strings, where the keys are usually strings. You will need to implement the Trie class with the following operations: insert, search, and startsWith.
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:
- Trie trie = new Trie();
- trie.Insert("apple");
- trie.Search("apple"); // returns true
- trie.Search("app"); // returns false
- trie.StartsWith("app"); // returns true
- trie.Insert("app");
- trie.Search("app"); // returns true
Example 2
- Input:
["Trie", "insert", "insert", "insert", "search", "startsWith", "search"]
[[], ["hello"], ["world"], ["hell"], ["world"], ["he"], ["hello world"]] - Output: [null, null, null, null, true, true, false]
- Explanation:
- Trie trie = new Trie();
- trie.Insert("hello");
- trie.Insert("world");
- trie.Insert("hell");
- trie.Search("world"); // returns true
- trie.StartsWith("he"); // returns true
- trie.Search("hello world"); // returns false
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) where m is key length
- Space Complexity: O(n * m) where n is number of keys and m is key 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
- Use a TrieNode class with children and isEndOfWord flag
- Each node should maintain links to child nodes
- For insert, traverse the trie and create new nodes if needed
- For search, traverse and check if the last node has isEndOfWord set to true
- For startsWith, just check if the prefix path exists in the trie