Implement Trie (Prefix Tree)
Store words letter by letter in a tree, so that whole words and word beginnings can both be looked up.
Write a class that stores words and answers two kinds of questions about them. It has three methods:
- The method
adds a word.insert(word) - The method
returnssearch(word) if exactly this word was inserted.true - The method
returnsstartsWith(prefix) if some inserted word begins withtrue .prefix
Words and prefixes use only the lowercase letters a to z. In the examples, the output lists what searchstartsWithinsert
Example 1
Output: true, false, true, true
Example 2
Output: true, false, false
The Idea
Type "ap" into a search box on your phone, and it can offer apple, app and apt as you type. All three words begin with the same two letters. The beginning of a word, like "app" in "apple", is called a prefix.
Example 1 shows why the two questions are different. After insert("apple")search("app")falsestartsWith("app")trueinsert("app")search("app")true
So the object has to remember two things: which letter sequences begin some stored word, and where each whole word ends. How can it store the words so that both questions are answered by following the letters, without checking every word one by one?
Write each word as a path, one letter per step, all starting from the same place. Look at the picture below. It shows the words of both examples: apple, app and apt.
Each box is a node, and the arrows between them are links, each labelled with one letter. Start at the box labelled root and follow the orange links: a, then p, then p. They lead to the box app. Going on along l and e reaches apple. At the box ap the path splits, because apt goes on with t where app goes on with p. The letters written inside a box are the ones spelled on the way to it.
The three words have 11 letters between them, yet the picture has only six boxes besides root. The words apple, app and apt share their first two links, and app is the start of apple. A tree of letter links like this, where every path from the root spells a prefix of some stored word, is called a trie, or prefix tree.
The teal boxes, marked "word end", are where an inserted word stops. That mark is what tells the two questions apart. The call startsWith("app")search("app")insert("app")search("app")false
Solution Approach
Why build a trie at all, when a set of words is simpler? Once that is answered, three things need settling: what a node holds, how insert
Keeping the words in a set
Why not keep the words in a HashSetsearchstartsWith("ap")startsWith("ap")
What a node holds
What does one box of the picture need to know? Its links, and whether a word ends there. With only the letters a to z, the links fit in an array of 26 slots, named nextnullchch - 'a'
A booleanisWord
As an optional change, a HashMap
Adding a path with insert
How does insert("apt")isWord
Answering search and startsWith
Both questions start with the same walk: from root, follow one link per letter. If a slot is nullfalsestartsWith("b")startsWithtruesearchtrueisWord
Leaving out that last check is a real trap. A version of searchtruesearch("app")
Java Solution
The class has these parts:
- The class
is one box of the picture, with its 26 links inNode and the word end mark innext .isWord - The field
is the box labelled root, an empty node where every walk starts.root - The method
follows the letters frominsert , creates each missing node, and setsroot on the last one.isWord - The private helper
follows the letters of a string fromwalk and returns the node it reaches, orroot when a link is missing.null - The methods
andsearch both callstartsWith . Onlywalk also checkssearch .isWord
The main
public class ImplementTrie {
private static class Node {
Node[] next = new Node[26]; // one slot per letter, 'a' to 'z'
boolean isWord; // true if an inserted word ends exactly here
}
private final Node root = new Node();
public void insert(String word) {
Node cur = root;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (cur.next[i] == null) cur.next[i] = new Node(); // create the path as needed
cur = cur.next[i];
}
cur.isWord = true;
}
public boolean search(String word) {
Node node = walk(word);
return node != null && node.isWord; // the path exists and a word ends there
}
public boolean startsWith(String prefix) {
return walk(prefix) != null; // the path exists
}
// Follows the letters of s from the root; null if the path breaks off.
private Node walk(String s) {
Node cur = root;
for (char ch : s.toCharArray()) {
cur = cur.next[ch - 'a'];
if (cur == null) return null;
}
return cur;
}
public static void main(String[] args) {
ImplementTrie trie = new ImplementTrie();
// Example 1
trie.insert("apple");
System.out.println("search(\"apple\") -> " + trie.search("apple"));
System.out.println("search(\"app\") -> " + trie.search("app"));
System.out.println("startsWith(\"app\") -> " + trie.startsWith("app"));
trie.insert("app");
System.out.println("search(\"app\") -> " + trie.search("app"));
// Example 2, on the same trie
trie.insert("apt");
System.out.println("startsWith(\"apt\") -> " + trie.startsWith("apt"));
System.out.println("search(\"ap\") -> " + trie.search("ap"));
System.out.println("startsWith(\"b\") -> " + trie.startsWith("b"));
// Edge cases
System.out.println("search(\"apples\") -> " + trie.search("apples"));
System.out.println("startsWith(\"\") -> " + trie.startsWith(""));
System.out.println("search(\"\") -> " + trie.search(""));
}
}
Running it prints:
search("apple") -> true
search("app") -> false
startsWith("app") -> true
search("app") -> true
startsWith("apt") -> true
search("ap") -> false
startsWith("b") -> false
search("apples") -> false
startsWith("") -> true
search("") -> false
Look at the two lines for search("app")falsetrueinsert("app")search("ap")falsestartsWith("b")false
Then comes search("apples") -> falsenullwalk("")rootstartsWith("")truesearch("")false
Complexity
Every call follows one link per letter, so its cost depends on the length of the word, not on how many words are stored.
- Time: O(L) per call, where L is the length of the word or prefix, because
andinsert do one array lookup per letter, andwalk creates at most one node per letter.insert - Space: O(T × 26), where T is the total number of letters inserted, because in the worst case no two words share a prefix and every letter gets its own node with a 26-slot array. Shared prefixes, like ap in the picture, use less.
Adding a wildcard letter to the search is