Trie
Implement a trie data structure with the following methods:
Trie()
constructs a new instance of a trieadd(String word)
adds a word into the trieexists(String word)
returns whetherword
exists in the triestartswith(String p)
returns whether there’s some word whose prefix isp
Constraints
n ≤ 100,000
wheren
is the number of calls toadd
,exists
andstartswith
https://binarysearch.com/problems/Trie
Examples
Example 1
Input
- methods =
['constructor', 'add', 'add', 'exists', 'startswith', 'exists']
- arguments =
[[], ['dog'], ['document'], ['dog'], ['doc'], ['doge']]
Output
- answer =
[None, None, None, True, True, False]
Explanation
- We create a
Trie
- We add the word
"dog"
to the trie - We add the word
"document"
to the trie - We check whether
"dog"
exists in the trie which it does - We check whether there is some word whose prefix is
"doc"
which there is ("document
) - We check whether
"doge"
exists in the trie which it does not
Leave a comment