Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
Build a class Trie with three methods:
insert(word): store the word.search(word): returntrueonly if this exact word was inserted.startsWith(prefix): returntrueif any inserted word begins withprefix.
All strings are lowercase English letters, up to 2,000 long, and there are up to 3 × 10⁴ calls in total.
Example:
insert("apple")
search("apple") → true
search("app") → false ("app" is only part of "apple")
startsWith("app") → true
insert("app")
search("app") → trueA trie (said "try", from retrieval) is also called a prefix tree.
Start with brute force
Keep a hash set of words. insert and search are O(L) each (hashing a string of length L), which is great.
The problem is startsWith. A hash set can't answer "does anything start with app?" without checking every stored word. With 3 × 10⁴ words of length 2,000, one call could cost 6 × 10⁷ character comparisons, and there can be thousands of calls.
You could also store every prefix of every word in a second set. That makes startsWith O(L), but a word of length 2,000 has 2,000 prefixes totalling about 2 million characters. Far too much memory.
Building the intuition
Think of a dictionary's thumb index. To find "apple", you don't read every word. You jump to a, then within that to ap, then app. Every word starting with "app" lives in the same place.
So store words the same way: as a tree where each edge is a letter. The root is the empty string. From the root, an a edge leads to the node for "a". From there, a p edge leads to "ap", and so on. A node is a prefix: the letters on the path from the root to it.
(root)
└─ a
└─ p
└─ p ← end of "app"
└─ l
└─ e ← end of "apple"Now startsWith("app") just walks a → p → p. If every edge exists, some word has that prefix. That's O(L), independent of how many words are stored.
But search("app") must tell "app was inserted" apart from "app exists only because apple passes through it". The path alone can't. So each node gets one more field: is_end, set to true on the node where an inserted word finishes.
The optimal approach
Each TrieNode has:
children: a map from letter to child node (or an array of 26 slots, indexc − 'a');is_end: true if an inserted word ends here.
Then:
insert(word): start at the root. For each letter, if that child is missing, create it. Move into it. After the last letter, setis_end = true.walk(s)(a helper): start at the root and follow each letter. If a child is missing, return null. Otherwise return the node you end on.search(word):walk(word)is not null and that node'sis_endis true.startsWith(prefix):walk(prefix)is not null.
The subtle detail is the difference between search and startsWith. It's one condition: the end flag. Forgetting it makes search("app") return true after only insert("apple").
Map or array? A 26-slot array is fastest and simplest in C++ and Java. A hash map uses less memory when nodes have few children, and it's the natural choice in Python and JavaScript. Both give O(L) per operation.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # does a whole inserted word stop here?
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode() # create only the missing part of the path
node = node.children[ch]
node.is_end = True
def search(self, word: str) -> bool:
node = self._walk(word)
# The path existing is not enough: "app" is a path inside "apple"
return node is not None and node.is_end
def startsWith(self, prefix: str) -> bool:
# For a prefix, the path existing IS enough
return self._walk(prefix) is not None
def _walk(self, s: str) -> Optional[TrieNode]:
# Follow s letter by letter; None means we fell off the tree
node = self.root
for ch in s:
if ch not in node.children:
return None
node = node.children[ch]
return nodestruct TrieNode {
TrieNode* children[26] = {}; // children[c - 'a'], nullptr if no word continues with c
bool isEnd = false; // does a whole inserted word stop here?
};
class Trie {
TrieNode* root;
// Follow s letter by letter; nullptr means we fell off the tree
TrieNode* walk(const string& s) {
TrieNode* node = root;
for (char ch : s) {
node = node->children[ch - 'a'];
if (node == nullptr) return nullptr;
}
return node;
}
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* node = root;
for (char ch : word) {
int i = ch - 'a';
if (node->children[i] == nullptr) {
node->children[i] = new TrieNode(); // create only the missing part of the path
}
node = node->children[i];
}
node->isEnd = true;
}
bool search(string word) {
TrieNode* node = walk(word);
// The path existing is not enough: "app" is a path inside "apple"
return node != nullptr && node->isEnd;
}
bool startsWith(string prefix) {
// For a prefix, the path existing IS enough
return walk(prefix) != nullptr;
}
};class Trie {
private static class TrieNode {
TrieNode[] children = new TrieNode[26]; // children[c - 'a'], null if no word continues with c
boolean isEnd = false; // does a whole inserted word stop here?
}
private final TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (node.children[i] == null) {
node.children[i] = new TrieNode(); // create only the missing part of the path
}
node = node.children[i];
}
node.isEnd = true;
}
public boolean search(String word) {
TrieNode node = walk(word);
// The path existing is not enough: "app" is a path inside "apple"
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
// For a prefix, the path existing IS enough
return walk(prefix) != null;
}
// Follow s letter by letter; null means we fell off the tree
private TrieNode walk(String s) {
TrieNode node = root;
for (char ch : s.toCharArray()) {
node = node.children[ch - 'a'];
if (node == null) return null;
}
return node;
}
}class TrieNode {
constructor() {
this.children = new Map(); // letter -> TrieNode
this.isEnd = false; // does a whole inserted word stop here?
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
/**
* @param {string} word
* @return {void}
*/
insert(word) {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) {
node.children.set(ch, new TrieNode()); // create only the missing part of the path
}
node = node.children.get(ch);
}
node.isEnd = true;
}
/**
* @param {string} word
* @return {boolean}
*/
search(word) {
const node = this.walk(word);
// The path existing is not enough: "app" is a path inside "apple"
return node !== null && node.isEnd;
}
/**
* @param {string} prefix
* @return {boolean}
*/
startsWith(prefix) {
// For a prefix, the path existing IS enough
return this.walk(prefix) !== null;
}
// Follow s letter by letter; null means we fell off the tree
walk(s) {
let node = this.root;
for (const ch of s) {
if (!node.children.has(ch)) return null;
node = node.children.get(ch);
}
return node;
}
}Dry run
insert("apple"), search("app"), startsWith("app"), insert("app"), search("app")
| Call | Walk | What happens | Returns |
|---|---|---|---|
insert("apple") | root → a → p → p → l → e | 5 new nodes; e gets is_end = true | — |
search("app") | root → a → p → p | path exists, but the second p has is_end = false | false |
startsWith("app") | root → a → p → p | path exists | true |
insert("app") | root → a → p → p | no new nodes; the second p gets is_end = true | — |
search("app") | root → a → p → p | path exists and is_end = true | true |
Inserting "app" after "apple" created zero nodes. That sharing is what makes tries efficient.
Complexity
- Time: O(L) for each
insert,searchandstartsWith, where L is the string's length. One step per letter, each step O(1). - Space: O(total letters inserted) in the worst case (no shared prefixes). Each node is O(26) with arrays or O(children) with maps.
Edge cases and traps
- Forgetting
is_endinsearch. The classic bug:searchthen behaves likestartsWith. - Inserting the same word twice. Walks the same path and sets the flag again. Harmless.
- A word that is a prefix of another, inserted second. Like "app" after "apple": no new nodes, just a flag. Make sure
insertdoesn't recreate existing children and wipe out the subtree. - Creating nodes in
search. If your walk uses something likesetdefaultorcomputeIfAbsent, a failed search adds junk nodes and laterstartsWithcalls lie. Onlyinsertshould create. - Searching a string longer than any word. The walk hits a missing child and returns null. Don't index past the end.
Say it in the interview
"A hash set handles search but not startsWith, so I'll use a trie. Each node has a children map, or a 26-slot array, and a flag saying a word ends there. Insert walks the word, creating missing nodes, and sets the flag on the last one. Both queries walk the same way. startsWith only needs the path to exist. search also needs the end flag, so 'app' isn't found just because 'apple' was inserted. Every operation is O(length of the string)."
Follow-ups interviewers ask
- "Add delete(word)." Walk to the end and clear
is_end. To free memory, recurse back up and remove nodes that now have no children and no end flag. - "Count how many words start with a prefix." Keep a
counton each node, incremented on every insert that passes through. Thenwalk(prefix).countis the answer. - "Support wildcards like
b.d." That's the next problem in this stage, Design Add and Search Words Data Structure: a trie plus DFS.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free