Problem overview
A trie, or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each child adds one more letter to it. Words that start the same way share the same path from the root.
The class Trie has three methods. insert(String word) adds a word. search(String word) returns true only if that exact word was inserted. startsWith(String prefix) returns true if some inserted word begins with prefix; a word counts as a prefix of itself. Each operation should take O(L) time, where L is the length of the word or prefix.
After insert("apple"), search("apple") is true, but search("app") is false because "app" is only the beginning of a longer word, while startsWith("app") is true. After insert("app"), search("app") becomes true.
Approach: one node per prefix, with an end flag
Storing the words in a set would answer search quickly, but startsWith would have to check every word. A trie answers both by walking down from the root, one letter per level, so the cost depends only on the length of the query.
Each node needs two things:
- its children: a map from the next letter to the child node for that letter;
- an end flag,
isEnd, that is true when an inserted word finishes at this node.
The flag is what separates "apple was inserted" from "apple's prefix exists". After inserting "apple", the nodes for "app" and "apple" both exist, but only the node for "apple" has isEnd set. The root stands for the empty prefix, and an empty trie is just a root with no children.
All three operations share the same walk. insert creates missing nodes along the way and marks the last one. search walks without creating anything and returns the flag of the last node. startsWith walks the same way and returns true if it never fell off the trie.
Step by step
- Give
TrieNodeachildrenfield of typeMap<Character, TrieNode>, initialised to a newHashMap. Map keys must be objects, so the key type isCharacter, the wrapper class ofchar. Java converts between them automatically. Because the field has an initial value, every new node gets its own empty map and the class needs no constructor. - Add the flag:
boolean isEnd = false. - Give
Triearootfield set tonew TrieNode(). - In
insert, start a variablenodeatrootand loop overword.toCharArray(). - For each letter, if
node.childrenhas no key for it (containsKey),puta newTrieNodeunder that letter. Then move down withnode = node.children.get(c). The child exists by now, whether it was already there or was just created. - After the loop, set
node.isEnd = true. This marks the word as inserted and not only as the start of a longer word. - In
search, do the same walk fromroot, but when a letter has no child, returnfalseat once: nothing was inserted along that path. After the loop, returnnode.isEnd. - In
startsWith, repeat the walk with the same earlyfalse. If the loop completes, the whole prefix exists as a path, and every node in a trie lies on the path of some inserted word, so returntrue.
The solution in Java
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isEnd = false;
}
class Trie {
TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (!node.children.containsKey(c)) {
node.children.put(c, new TrieNode());
}
node = node.children.get(c);
}
node.isEnd = true;
}
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);
}
return node.isEnd;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);
}
return true;
}
}
Java details worth understanding:
- Autoboxing.
containsKey(c),put(c, ...)andget(c)take an object, and thecharcis boxed into aCharacterfor each call. Passing anintsuch as99instead would box to anInteger, which is a different key type and would never match. HashMap.getreturnsnullfor a missing key. The code testscontainsKeyfirst, sogetis only called for a key that exists. Callinggetand checking fornullwould also work, and does one lookup instead of two.toCharArray()turns aStringinto achar[], which the for-each loop walks one letter at a time.- Imports.
MapandHashMapare injava.util, so a file of your own needsimport java.util.*;. - Package-private members. The fields have no modifier, so other classes in the same package can reach them. That is fine for a small exercise.
Complexity
Time: O(L) per operation. Each loop turn does one hash lookup, one possible insertion and one move down, and the loop runs once per letter. These map operations take constant time on average.
Space: O(total letters) in the worst case, for the words inserted: a new node is created for each letter that isn't already on a path. Words that share prefixes share nodes, so the real cost is often lower.
Edge cases and common mistakes
- Prefix against word. After inserting "car" and "cart",
startsWith("ca")istrueandsearch("ca")isfalse, since no word ended at "ca". - Returning
truefromsearchafter the walk. The path being present isn't enough. The method must returnnode.isEnd. - Inserting a word twice. After inserting "dog" twice, nothing changes: the nodes exist and
isEndis set again.search("dog")istrue. - A word that is a prefix of itself.
startsWith("dog")istrueafter inserting "dog". - Longer than anything inserted.
startsWith("dogs")andsearch("dogs")are bothfalseafter inserting only "dog": the walk falls off at "s". - Creating nodes inside
search. A query must not change the trie, or later queries will see words that were never inserted.
Testing
These results come from running the class:
- Insert "apple", then
search("apple"),search("app"),startsWith("app"):true,false,true. Insert "app", thensearch("app"):true. - Insert "car", "cart", then
startsWith("ca"),search("ca"),startsWith("cat"),search("cart"):true,false,false,true. - Insert "dog" twice, then
search("dog"),startsWith("dog"),search("do"),startsWith("dogs"),search("dogs"):true,true,false,false,false.
