
Problem
Solution
Submissions
Trie with Insert, Search, and startsWith Methods
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 12
Write a C# program to implement a Trie data structure with the following methods: 1. `Insert(word)`: Inserts a word into the trie. 2. `Search(word)`: Returns true if the word exists in the trie, false otherwise. 3. `StartsWith(prefix)`: Returns true if there is a word in the trie that starts with the given prefix, false otherwise.
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"], ["hi"], ["hello"], ["wo"], ["hey"]] - Output: [null, null, null, null, true, true, false]
- Explanation:
- Trie trie = new Trie();
- trie.Insert("hello");
- trie.Insert("world");
- trie.Insert("hi");
- trie.Search("hello"); // returns true
- trie.StartsWith("wo"); // returns true
- trie.Search("hey"); // returns false
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 all operations, where m is the key length
- Space Complexity: O(n * m) where n is the number of keys and m is the average 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 tree-like data structure where each node represents a single character
- Each node should contain links to child nodes for each possible character
- Use a boolean flag in each node to mark the end of a word
- For the insert operation, create nodes for each character if they don't exist
- For the search operation, follow the path in the trie and check if the last node is marked as the end of a word
- For the startsWith operation, just follow the path in the trie without checking the end-of-word flag