Implement Trie (prefix tree) solution explained
A trie (prefix tree) stores words letter by letter: each node maps a character to a child node and carries a flag saying whether a word ends there. Insert walks down creating missing children and sets the flag; search walks down and checks the flag; a prefix check only needs the walk to succeed. Each operation takes O(L) time for a word of length L, no matter how many words are stored.
By Evin JohnPublished 7 min read
The problem, in plain terms
Design a class that holds a growing collection of lowercase words. It needs three operations: add a word; report whether a given word was added exactly; and report whether any added word starts with a given prefix. Calls arrive in any order and in any number, so each one should be fast even after many insertions.
insert("car"), insert("cart"), insert("care"), insert("dog")
search("car") -> true (added exactly)
search("ca") -> false (only a prefix)
startsWith("ca") -> true (car, cart and care begin with it)
startsWith("cat") -> false
search("cart") -> true
(root)
/ \
c d
| |
a o
| |
r* g*
/ \
t* e* * = a word ends hereQuestions to settle first: is the alphabet only lowercase English letters, can words repeat, can the empty string be inserted or queried, and roughly how many words and calls to expect? The alphabet question decides between an array of 26 children and a hash map.
How the problem is used in interviews
It tests whether you can design a small data structure from a description, pick a node representation, and keep the code tidy across several methods. It is also the foundation for harder questions: autocomplete, word games on a grid, spell checking, and longest common prefix. Interviewers often follow with "how would you delete a word" or "how would you count words with a prefix".
A slower starting idea
Keep the words in a hash set. Exact search is then O(L) on average, which is fine, but a prefix check has to scan every stored word and compare its start, which is O(N × L) for N words. Sorting the words and binary searching for the prefix brings the check to O(L log N) but makes insertion O(N) to keep the list sorted. The trie gives O(L) for all three operations.
class WordList:
def __init__(self):
self.words = set()
def insert(self, word):
self.words.add(word)
def search(self, word):
return word in self.words
def starts_with(self, prefix):
return any(w.startswith(prefix) for w in self.words)The optimal approach: a prefix tree
Pattern: trie. The root is an empty node. To insert, start at the root and, for each character, move to that child, creating it if it is missing; at the last character, set the end flag. Search follows the same path without creating anything and returns the end flag of the final node, or false if the path breaks. A prefix check follows the path too, but only needs to know that some stored word lies at or below where it stops.
class TrieNode:
__slots__ = ("children", "is_word")
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_word = False # does a stored word end here?
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_word = True
def _walk(self, text):
node = self.root
for ch in text:
node = node.children.get(ch)
if node is None:
return None
return node
def search(self, word):
node = self._walk(word)
return node is not None and node.is_word
def starts_with(self, prefix):
node = self._walk(prefix)
# an empty trie still has a root, so also check a word lies below
return node is not None and (node.is_word or bool(node.children))class Trie {
constructor() {
this.root = { next: new Map(), end: false };
}
insert(word) {
let node = this.root;
for (const ch of word) {
if (!node.next.has(ch)) node.next.set(ch, { next: new Map(), end: false });
node = node.next.get(ch);
}
node.end = true;
}
#find(text) {
let node = this.root;
for (const ch of text) {
node = node.next.get(ch);
if (node === undefined) return null;
}
return node;
}
search(word) {
const node = this.#find(word);
return node !== null && node.end;
}
startsWith(prefix) {
const node = this.#find(prefix);
// an empty trie still has a root, so also check a word lies below
return node !== null && (node.end || node.next.size > 0);
}
}Why the extra check in the prefix method: every node except the root exists only because some word passed through it, so reaching one proves a match. The root exists even when nothing was inserted, so an empty prefix on an empty trie must return false. Our first draft returned true there; random testing against the set-based version caught it. Many problem versions rule out empty strings, but saying this out loud shows care.
Common follow-ups
- Count the words that start with a prefix. Store in each node how many words pass through it, incrementing on insert (only when the word is new). The answer is the count at the prefix node.
- Delete a word. Walk to the end, clear the flag, then on the way back remove child nodes that have no flag and no children. A recursive helper or a stack of the path both work.
- Return all words with a prefix, for autocomplete. Walk to the prefix node, then run a depth-first search below it, building strings as you go; cap the number of results.
- Array or map for children? A fixed array of 26 is fast and simple for lowercase English but wastes memory in sparse tries; a map adapts to any alphabet.
Complexity summary
| Approach | Insert | Search | Prefix check | Space |
|---|---|---|---|---|
| Hash set | O(L) | O(L) | O(N × L) | O(S) |
| Sorted list with binary search | O(N) to keep order | O(L log N) | O(L log N) | O(S) |
| Trie | O(L) | O(L) | O(L) | O(S) nodes in the worst case |
Edge cases to try
- Searching for a word that is only a prefix of a stored word (car stored, ca searched).
- Searching for a word longer than any stored word.
- Inserting the same word twice.
- An empty prefix, on an empty trie and on a non-empty one.
- Inserting the empty string, if allowed: the root's flag becomes true.
Pitfalls
- Returning true from search whenever the path exists, ignoring the end flag.
- Creating nodes during search or prefix checks, which grows the trie on every query.
- Sharing one mutable default dictionary between nodes (a classic Python mistake with default arguments).
- Forgetting that the root exists even when the trie is empty.
- Using an array of 26 when the input may contain uppercase letters or other characters.
How to explain it out loud
Fictional example
- Candidate
- I'll use a tree where each edge is a letter, so words with the same beginning share a path. Each node has a map of children and a flag for whether a word ends there.
- Candidate
- Insert walks down creating missing children and sets the flag. Search walks down and checks the flag, because car being stored doesn't mean ca is. The prefix check only needs the walk to succeed, plus a guard for the empty trie.
- Candidate
- All three are O(L) in the query length, independent of how many words are stored. If the alphabet were fixed and small I might use arrays instead of maps.
Related problems
A trie earns its keep in Word Search II, where it lets one grid search look for many words at once. Before that, the single-word version, Word Search, covers the backtracking on its own. Designing an encoding with a clean interface is also the core of Serialize and Deserialize Binary Tree.
Using Natively to practice
Data structure design rounds go better when you have practiced describing the interface before typing. Natively can read a design prompt from a screenshot during practice on Mac or Windows, suggest a node layout and the follow-ups to expect, and transcribe the mock so you can check that you mentioned the end-of-word flag and the empty cases. See the AI interview assistant.
Questions people ask
How do you implement a trie?
Give each node a map from character to child and a flag marking the end of a word. Insert walks down creating missing children and sets the flag; search walks down and returns the flag; startsWith returns whether the walk succeeds and a word lies at or below that node.
What is the time complexity of trie operations?
Insert, search and prefix checks each take O(L) time for a string of length L, independent of how many words are stored. Space is proportional to the total characters inserted in the worst case.
Why does a trie need an end-of-word flag?
Because a path existing only proves that some stored word starts with those letters. The flag tells you whether a word ends exactly there, so search for ca returns false when only car is stored.
Should trie children be an array or a hash map?
An array of 26 is fast for lowercase English letters but wastes memory when nodes have few children. A hash map handles any alphabet and sparse tries better.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
