Implement Trie (Prefix Tree)
Design and implement a 26-way prefix tree with insert, search, and startsWith operations in O(L) time.
01The problem
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()Initializes the trie object.void insert(String word)Inserts the stringwordinto the trie.boolean search(String word)Returnstrueif the stringwordis in the trie (i.e., was inserted before), andfalseotherwise.boolean startsWith(String prefix)Returnstrueif there is a previously inserted stringwordthat has the prefixprefix, andfalseotherwise.
02How to spot it
- Many words share common prefixes.
- Queries require checking whether a word exists or whether any word starts with a given prefix.
- Standard hash sets can check exact words in
O(L)time, but checkingstartsWith(prefix)would require storing all prefixes of all words, consumingO(N · L^2)memory. - A Trie achieves
O(L)lookup and prefix verification while sharing prefix storage.
03Pseudocode
insert(w):
node = root
for ch in w:
create child ch if missing
node = child ch
node.isWord = true
search(w): walk(w) exists and isWord
startsWith(p): walk(p) exists04Watch it work
trie state
empty root
Initialize Trie root with empty 26-way children slots and isWord = false.
Pseudocode
- insert(w):
- node = root
- for ch in w:
- create child ch if missing
- node = child ch
- node.isWord = true
- search(w): walk(w) exists and isWord
- startsWith(p): walk(p) exists
Variables
- storedWords
05Step-by-step dry run
insert("apple"):- Walk from root: create nodes for
'a','p','p','l','e'. - Mark terminal node for
'e'withisWord = true.
- Walk from root: create nodes for
search("apple"):- Follow path
a -> p -> p -> l -> e. - Node exists and
isWord == true-> returntrue.
- Follow path
search("app"):- Follow path
a -> p -> p. - Node exists, but
isWord == false(only "apple" was inserted) -> returnfalse.
- Follow path
startsWith("app"):- Follow path
a -> p -> p. - Node exists -> return
true(words like "apple" branch below it).
- Follow path
insert("app"):- Follow path
a -> p -> p(no new nodes needed). - Set
isWord = trueon the second'p'node.
- Follow path
search("app"):- Follow path
a -> p -> p. - Node exists and now
isWord == true-> returntrue.
- Follow path
06Java solution
public class Main {
static class Trie {
private final Trie[] next = new Trie[26];
private boolean isWord;
public Trie() {}
public void insert(String word) {
Trie node = this;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (node.next[i] == null) {
node.next[i] = new Trie();
}
node = node.next[i];
}
node.isWord = true;
}
public boolean search(String word) {
Trie node = walk(word);
return node != null && node.isWord;
}
public boolean startsWith(String prefix) {
return walk(prefix) != null;
}
private Trie walk(String s) {
Trie node = this;
for (char ch : s.toCharArray()) {
node = node.next[ch - 'a'];
if (node == null) return null;
}
return node;
}
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple"));
System.out.println(trie.search("app"));
System.out.println(trie.startsWith("app"));
trie.insert("app");
System.out.println(trie.search("app"));
}
}true false true true
07Why it works
Every stored word corresponds to exactly one path from the root, and words with a common prefix share that part of the path. Following a string letter by letter either fails (no word has this prefix) or reaches a node. The helper method walk(s) encapsulates path traversal, so search and startsWith share identical logic except that search additionally verifies node.isWord == true.
08Time and space
- Time complexity:
insert(word):O(L)whereLis the length of the word.search(word):O(L)character comparisons.startsWith(prefix):O(P)wherePis prefix length.
- Space complexity:
O(totalCharacters · 26)in the worst case where no words share prefixes.
09Edge cases
searchbefore any insertion:walk(word)returnsnull-> returnsfalse.- Inserting a prefix of an already inserted word: Reuses existing path; only sets
isWord = trueon the existing node without allocating new nodes. startsWith(""): Empty prefix matches root -> returnstrue.
10Common mistakes
- Returning
trueinsearchwhennode != nullbut!node.isWord: A path existing only means the string is a prefix; checkingnode.isWordis necessary to confirm a full word. - Creating new nodes during search: Search should only read existing links; creating nodes pollutes the trie with fake paths.
11Other approaches
- HashMap for children:
Map<Character, TrieNode> nextsaves memory when alphabet size is large or sparse (e.g. Unicode), but an array of 26 references is faster for lowercase English letters.
12In the interview
- Mention the shared helper method: "I will implement a private
walk(String s)helper method to avoid duplicating the letter-by-letter traversal betweensearchandstartsWith." - Note alphabet size: for
a-z, an array of 26 elements gives instantO(1)index lookups with minimal overhead.
13Quiz
What distinguishes search(word) from startsWith(prefix) in a Trie?
- (Recommended) search requires node.isWord to be true, while startsWith only requires the path to exist
- search is O(1) while startsWith is O(n)
- startsWith creates nodes while search does not
- search only inspects the root node
Answer: search requires node.isWord to be true, while startsWith only requires the path to exist. A prefix path may exist in the trie because a longer word was inserted, but it is only a valid word if isWord was explicitly flagged.
14Solve it yourself
Open LeetCode #208 and submit the Trie implementation.