Prefix Tree
Intro
We can consider trie as a space efficient hash table for words. It supports add(word) and contains(word) in O(len(word)) time. Trie saves space because it stores words with common prefixes under the same path.
Implement Trie (LC.208)
Implement a trie with insert, search, and startsWith methods.
insert - Inserts a word into the trie
search - Returns if the word is in the trie
startsWith - Returns if there is any word in the trie that starts with the given prefix
Example
Trie trie = new Trie();
trie.insert("lol");
if (trie.search(word)) freqMap.get(word)++;
if (trie.startsWith(prefix)) freqMap.get(prefix)++;Analysis
Trie is a n-ary tree depending on the number of available characters. Each node should hold its children map, (and its own key?), and isWord boolean. Internally, we want to store a dummyRoot to signify the empty string prefix.
Code
Follow Up #1 (LC.211)
The search query can contain . which matches any character.
Example
Analysis
Before, we use a travel pointer to travel down a path (just like traversing a linked list). Now, in order to support ., we need to explore an entire subtree to find a match. Preform a DFS on all the possible children at that level and then figure out one path that matches with the given word.
Code
Follow Up #2
The search query can contain * which can match 0 or more previous character.
References
UMD CS420 Lecture 23 Tries & Suffix Trees
Implement Trie Editoral Solution
Wikipedia Prefix Tree, Compact Prefix Tree
Last updated