Implement Trie (Prefix Tree)
Medium · Tries
Jump to codeImplement insert(word), search(word), and startsWith(prefix) for lowercase words. Search requires a whole stored word; startsWith only requires a matching prefix.
Examples
Example 1
operations = ["insert","search","search","startsWith","insert","search"] words = ["apple","apple","app","app","app","app"]
Output: [true,false,true,true]
Example 2
operations = ["insert","search","startsWith"] words = ["hello","hello","he"]
Output: [true,true]
Constraints
- 1 <= word.length, prefix.length <= 1000
- word and prefix are made up of lowercase English letters.
Function contract
Implement Trie with insert(word), search(word), and startsWith(prefix). Each case starts a new Trie. The grader returns only the boolean results of search and startsWith; insert has no output.
Need a hint?
A path and a complete word are different states.
Asked in real interviews
Candidates reported versions of Implement Trie (Prefix Tree) from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Store child edges by character and an end-of-word flag at each node. Insert creates missing nodes then marks the endpoint. Both lookups walk the requested path; search additionally checks the flag. Prefix lookup succeeds when its path exists.
Complexity
O(L) time per operation for length L; O(total inserted characters) space.
Python reference solution
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for char in word:
node = node.setdefault(char, {})
node['$'] = True
def search(self, word):
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return '$' in node
def startsWith(self, prefix):
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
JavaScript solution
class Trie {
constructor() { this.root = {children: new Map(), end: false}; }
insert(word) {
let node = this.root;
for (const c of word) {
if (!node.children.has(c)) node.children.set(c, {children: new Map(), end: false});
node = node.children.get(c);
}
node.end = true;
}
walk(text) {
let node = this.root;
for (const c of text) {
if (!node.children.has(c)) return null;
node = node.children.get(c);
}
return node;
}
search(word) {
const node = this.walk(word);
return node !== null && node.end;
}
startsWith(prefix) { return this.walk(prefix) !== null; }
}
Java solution
class Trie {
private static class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean end;
}
private final TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (node.children[i] == null) node.children[i] = new TrieNode();
node = node.children[i];
}
node.end = true;
}
private TrieNode walk(String text) {
TrieNode node = root;
for (char c : text.toCharArray()) {
node = node.children[c - 'a'];
if (node == null) return null;
}
return node;
}
public boolean search(String word) {
TrieNode node = walk(word);
return node != null && node.end;
}
public boolean startsWith(String prefix) { return walk(prefix) != null; }
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Trie {
struct TrieNode {
array<int, 26> children;
bool end = false;
TrieNode() { children.fill(-1); }
};
vector<TrieNode> nodes{1};
int walk(const string& text) {
int node = 0;
for (char c : text) {
node = nodes[node].children[c - 'a'];
if (node == -1) return -1;
}
return node;
}
public:
void insert(string word) {
int node = 0;
for (char c : word) {
int i = c - 'a';
if (nodes[node].children[i] == -1) {
int next = nodes.size();
nodes.emplace_back();
nodes[node].children[i] = next;
}
node = nodes[node].children[i];
}
nodes[node].end = true;
}
bool search(string word) {
int node = walk(word);
return node != -1 && nodes[node].end;
}
bool startsWith(string prefix) { return walk(prefix) != -1; }
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
"insert",
"search",
"search",
"startsWith",
"insert",
"search"
],
[
"apple",
"apple",
"app",
"app",
"app",
"app"
]
][ true, false, true, true ]
[
[
"insert",
"search",
"startsWith"
],
[
"hello",
"hello",
"he"
]
][ true, true ]
[
[
"search",
"startsWith"
],
[
"a",
"a"
]
][ false, false ]
[
[
"insert",
"insert",
"search",
"startsWith"
],
[
"app",
"apple",
"app",
"apple"
]
][ true, true ]
[
[
"insert",
"search",
"startsWith",
"search"
],
[
"dog",
"do",
"do",
"dog"
]
][ false, true, true ]
Drafts are saved per language in this browser when storage is available.