Implement Trie (Prefix Tree)
Medium
Topics
Implement a trie with insert(word), search(word) (returns whether the exact word was inserted), and startsWith(prefix) (returns whether any inserted word has the given prefix).
Example 1
Each node holds one character and a map of children, so a shared prefix is stored once rather than per word. That is what makes
startsWith cheap.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["Trie","insert","search","search","startsWith","insert","search"], values = [[],["apple"],["apple"],["app"],["app"],["app"],["app"]] Output: [null,null,true,false,true,null,true]
Constraints
- 1 <= word.length, prefix.length <= 2000
- Words consist of lowercase English letters.
- At most 3*10^4 calls.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A trie stores words along shared prefixes. Each node has up to 26 children and a flag marking the end of a complete word, so both exact search and prefix search walk the same path.
Approach
- Each node holds a children map and an
isEndflag. - insert walks/creates nodes for each character, marking the last as end.
- search walks the path and checks isEnd; startsWith walks the path and only checks it exists.
Dry Run
insert "apple", then insert "app"
Each node is itself a Trie -- a map of child letters plus one boolean. After both
inserts:
a
p
p (end)
l
e (end)
insert apple -> null
search apple -> true walk a-p-p-l-e, end is set
search app -> false the node exists, but its end flag is not set yet
startsWith app -> true the node exists, and that is all startsWith asks
insert app -> null sets end on the existing node; no new nodes created
search app -> true
answer null|null|true|false|true|null|true
Rows 3 and 4 are the entire reason this data structure exists. Both walk to the
same node; they disagree because search consults `end` and startsWith does not.
Drop the flag check from search and "app" reports true after only "apple" was
inserted -- which collapses the one distinction the trie is there to make.
The second insert adds no nodes at all. It walks the existing a-p-p path and only
flips a boolean, which is what makes a trie compact on a dictionary of words
sharing prefixes.
Nodes carry no character of their own. The letter lives on the EDGE, which is why
`ch` is a map keyed by character rather than a field on the node -- a node is
"whatever you reach by spelling this prefix".Complexity
- Time — O(L): each operation walks the word length L.
- Space — O(total chars): nodes for every distinct prefix.
Common Pitfalls
searchhas to checkend;startsWithmust not. Dropping the flag check makessearch("app")return true after only"apple"was inserted, which is the one distinction the data structure exists to make.- The node needs no character of its own. The edge into a node carries the letter, which is why
chis a map keyed by character rather than a field on the node.
Full Solution — all languages
class Trie:
def __init__(self):
self.ch = {}
self.end = False
def insert(self, word):
node = self
for c in word:
node = node.ch.setdefault(c, Trie())
node.end = True
def _find(self, word):
node = self
for c in word:
if c not in node.ch:
return None
node = node.ch[c]
return node
def search(self, word):
n = self._find(word)
return n is not None and n.end
def startsWith(self, prefix):
return self._find(prefix) is not Noneimport java.util.*;
class Trie {
Map<Character, Trie> ch = new HashMap<>();
boolean end = false;
public Trie() {
}
public void insert(String w) {
Trie n = this;
for (char c : w.toCharArray()) {
n.ch.putIfAbsent(c, new Trie());
n = n.ch.get(c);
}
n.end = true;
}
Trie find(String w) {
Trie n = this;
for (char c : w.toCharArray()) {
if (!n.ch.containsKey(c)) return null;
n = n.ch.get(c);
}
return n;
}
public boolean search(String w) {
Trie n = find(w);
return n != null && n.end;
}
public boolean startsWith(String p) {
return find(p) != null;
}
}#include <bits/stdc++.h>
using namespace std;
struct Trie {
map<char, Trie*> ch;
bool end = false;
Trie() {
}
void insert(string w) {
Trie* n = this;
for (char c : w) {
if (!n->ch.count(c)) n->ch[c] = new Trie();
n = n->ch[c];
}
n->end = true;
}
Trie* find(string w) {
Trie* n = this;
for (char c : w) {
if (!n->ch.count(c)) return nullptr;
n = n->ch[c];
}
return n;
}
bool search(string w) {
Trie* n = find(w);
return n && n->end;
}
bool startsWith(string p) {
return find(p) != nullptr;
}
};class Trie {
constructor() {
this.ch = {};
this.end = false;
}
insert(w) {
let n = this;
for (const c of w) {
if (!n.ch[c]) n.ch[c] = new Trie();
n = n.ch[c];
}
n.end = true;
}
_find(w) {
let n = this;
for (const c of w) {
if (!n.ch[c]) return null;
n = n.ch[c];
}
return n;
}
search(w) {
const n = this._find(w);
return n !== null && n.end;
}
startsWith(p) {
return this._find(p) !== null;
}
}