Google Questions
Implement a trie (prefix tree) that supports insert, search, and startsWith operations.
HardTechnicalData Structures15-20 minutes
Model Answer
A trie is a tree-like data structure where each node represents a character. Paths from root to nodes represent prefixes, and nodes can be marked as word-endings. Tries enable O(L) operations where L is the length of the word, with excellent prefix search capabilities.
Each node has a children map (character -> child node) and a boolean isEnd flag.
Approaches
Standard Trie with Map
Each node uses a Map for children, supporting any character set. Three methods traverse the trie character by character.
class TrieNode {
constructor() {
this.children = new Map();
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char);
}
node.isEnd = true;
}
search(word) {
const node = this._traverse(word);
return node !== null && node.isEnd;
}
startsWith(prefix) {
return this._traverse(prefix) !== null;
}
_traverse(str) {
let node = this.root;
for (const char of str) {
if (!node.children.has(char)) return null;
node = node.children.get(char);
}
return node;
}
}Time: O(L) for all operations where L is word lengthSpace: O(total characters across all words)
Common Mistakes
- 1.Not distinguishing between search (exact match with isEnd) and startsWith (prefix existence)
- 2.Using an array of 26 for children when the problem could involve more characters
- 3.Forgetting the isEnd flag entirely, making search equivalent to startsWith
- 4.Not handling empty string input
Follow-up Questions
- How would you implement autocomplete (return all words with a given prefix)?
- How would you optimize memory for a trie with many shared prefixes?
- What are the trade-offs between a trie and a hash map for string lookups?