Some basic skeleton code for the following problems can be found here, with some helpful details filled in and a few (very) cursory test cases. Feel free to develop your code on a computer and see if it works!
A basic and non-generic TrieNode
class for a Set of Strings is defined as follows:
class TrieNode {
HashMap<String, TrieNode> children;
boolean terminates;
}
Implement the insert
operation, which is an instance method of the TrieNode
class:
/** Insert word into the Set represented by this trie.
* Returns whether the Set changed. Precondition: word is not null. */
public boolean insert(String word) {
// your code here
}
Write code for the following method, which is a static method that takes a TrieNode
as an argument:
/** Return the number of words in the trie rooted at n that begin with
* the given prefix. If the prefix itself is a word, that is counted.
* Precondition: prefix is not null. */
public static int prefixFrequency(TrieNode n, String prefix) {
// your code here
}
What’s the worst-case runtime of the method from Problem 2?
Suppose we need to calculate prefix frequencies more efficiently than that.
Modify the TrieNode
class above to support a prefixFrequency
that operates in constant time (you’ll need to use some extra storage in exchange for a faster runtime).
Write code for prefixFrequency
(same spec as above) that operates on your modified TrieNode
and runs in O(1) time.
Modify your code for insert
(same spec as above) to work with the modified TrieNode
.