When this article is done (2020-07-13), there are 17 LeetCode problems about Trie (Prefix Tree). Among them, 2 problems are easy, 8 are medium, and 7 are hard.
Here we summarize four of them. Once you figure them out, Trie
should not be a challenge to you anymore. Hope this article is helpful to you.
The main interface of a trie should include the following:
insert(word)
: Insert a wordsearch(word)
: Search for a wordstartWith(prefix)
: Search for a word with the given prefix
Among all of the above, startWith
is one of the most essential methods, which leads to the naming for 'Prefix Tree'. You can start with 208.implement-trie-prefix-tree to get yourself familiar with this data structure, and then try to solve other problems.
Here's the graph illustration of a trie:
As the graph shows, each node of the trie would store a character and a boolean isWord
, which suggests whether the node is the end of a word. There might be some slight differences in the actual implementation, but they are essentially the same.