15% off all plans & roadmaps Use code
See plansImplement Trie (Prefix Tree)
- LeetCode 208
- Medium
- Design Patterns
- Tries
Updated
TL;DR: Build a data structure that stores words and answers exact-word and prefix queries. A trie stores one character per node, so every operation costs time proportional to the word length, not the number of stored words.
Problem
A trie (pronounced "try") or prefix tree is a tree data structure that stores and retrieves keys from a set of strings efficiently. Typical uses include autocomplete and spell checking.
Implement the Trie class:
Trie()creates an empty trie.void insert(String word)adds the stringwordto the trie.boolean search(String word)returnstrueifwordwas inserted earlier, andfalseotherwise.boolean startsWith(String prefix)returnstrueif some previously inserted word begins withprefix, andfalseotherwise.
Example 1
Input: ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output: [null, null, true, false, true, null, true]
Explanation:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns trueConstraints
1 <= word.length, prefix.length <= 2000wordandprefixconsist only of lowercase English letters.- At most
3 * 10^4calls in total are made toinsert,search, andstartsWith.
Constraints that matter
- Words can be 2000 characters long, so any approach that does work proportional to the length squared per insert costs up to 4 million steps per call. With 3 * 10^4 calls that is too heavy in the worst case.
- Up to 3 * 10^4 total calls means a scan over every stored word on each
startsWithis the number to beat. A scan costs (stored words) * (prefix length) per query. - Only lowercase letters a to z appear, so each node can hold a fixed array of 26 child slots and index it with
c - 'a'. - Calls are mixed in any order, so you cannot batch or sort the words up front. The structure must answer queries after every single insert.
Hints
Hint 1
This is a trie problem.
Hint 2
Keep every inserted word in a plain list.
Solution
Intuition
This is a trie problem. The giveaway is the startsWith method. Exact lookup is easy with a hash set, but a prefix query asks about the beginning of words, and a hash set has no notion of beginnings.
Picture a set of nested folders, one per letter, where opening a folder adds one letter to the prefix. The root is the outermost folder, and the isEnd flag is a sticky note marking that a complete word is filed there.
The move is to stop treating a word as one unit. Store it as a path of characters from a root node. Words that share a start share the first nodes of their paths, so app and apple use the same three nodes.
That shared structure answers both queries by walking. To check a prefix, follow its letters from the root. If every step finds a child, some inserted word passes through that node, so the prefix exists. If a step finds nothing, no word has that prefix.
Exact search needs one extra fact. Reaching the node for app only proves that app is a prefix of something. You also need a flag on the node saying a word ended there.
Insert apple and the nodes for a, p, p, l, e exist, but only the node for e has the flag. So search("app") fails and startsWith("app") succeeds. Each query walks at most one node per character, so cost depends on the query length and not on how many words are stored.
Worked example
Input: operations = ["Trie", "search", "startsWith"], arguments = [[], ["a"], ["a"]] Output: [null, false, false] Explanation: The constructor makes an empty trie. Nothing was inserted, so no word equals "a" and no word starts with "a". Both queries return false, and the constructor returns null.
Approach 1: Brute force: list of words
Keep every inserted word in a plain list. insert appends the word. search compares the query against each stored word. startsWith checks each stored word for the given prefix.
This is correct and takes only a few lines, so it is where a beginner starts. It ignores the fact that words share beginnings, which is exactly the structure the problem asks you to use.
Steps
- Create an empty list
wordsin the constructor. - In
insert, append the word to the list. - In
search, loop overwordsand return true if any entry equals the query. - In
startsWith, loop overwordsand return true if any entry begins with the prefix. - Return false when the loop finishes without a match.
Dry run
Trace the example. The constructor sets words = [].
search("a"): the loop body never runs because the list is empty. Returnfalse.startsWith("a"): same empty loop. Returnfalse.
The output is [null, false, false]. With apple inserted first, startsWith("app") would compare app against apple, find a match on the first entry, and return true. A miss has to look at every stored word.
Complexity
| Time | O(1) insert, O(N * L) search and startsWith |
|---|---|
| Space | O(N * L) |
Let N be the number of stored words and L the length of the longest string involved. insert appends once, which is O(1) amortized. search and startsWith visit up to N words and each comparison costs up to L characters, so one query costs O(N * L). Storage holds every word in full, which is O(N * L) characters. With 3 * 10^4 calls and 2000-character words this approach can reach billions of character comparisons.
PythonTested in our runner
from typing import List, Optional
class Trie:
def __init__(self):
self.words = []
def insert(self, word: str) -> None:
self.words.append(word)
def search(self, word: str) -> bool:
for w in self.words:
if w == word:
return True
return False
def startsWith(self, prefix: str) -> bool:
for w in self.words:
if w.startswith(prefix):
return True
return False
JavaTested in our runner
import java.util.*;
class Trie {
private List<String> words;
public Trie() {
words = new ArrayList<>();
}
public void insert(String word) {
words.add(word);
}
public boolean search(String word) {
for (String w : words) {
if (w.equals(word)) {
return true;
}
}
return false;
}
public boolean startsWith(String prefix) {
for (String w : words) {
if (w.startsWith(prefix)) {
return true;
}
}
return false;
}
}
C++Tested in our runner
#include <vector>
#include <string>
using namespace std;
class Trie {
vector<string> words;
public:
Trie() {
}
void insert(string word) {
words.push_back(word);
}
bool search(string word) {
for (const string& w : words) {
if (w == word) {
return true;
}
}
return false;
}
bool startsWith(string prefix) {
for (const string& w : words) {
if (w.rfind(prefix, 0) == 0) {
return true;
}
}
return false;
}
};
JavaScriptTested in our runner
var Trie = function() {
this.words = [];
};
/**
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
this.words.push(word);
};
/**
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
for (const w of this.words) {
if (w === word) {
return true;
}
}
return false;
};
/**
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
for (const w of this.words) {
if (w.startsWith(prefix)) {
return true;
}
}
return false;
};
GoTested in our runner
import "strings"
type Trie struct {
words []string
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) insert(word string) {
this.words = append(this.words, word)
}
func (this *Trie) search(word string) bool {
for _, w := range this.words {
if w == word {
return true
}
}
return false
}
func (this *Trie) startsWith(prefix string) bool {
for _, w := range this.words {
if strings.HasPrefix(w, prefix) {
return true
}
}
return false
}
C#Tested in our runner
public class Trie {
private List<string> words;
public Trie() {
words = new List<string>();
}
public void insert(string word) {
words.Add(word);
}
public bool search(string word) {
foreach (string w in words) {
if (w == word) {
return true;
}
}
return false;
}
public bool startsWith(string prefix) {
foreach (string w in words) {
if (w.StartsWith(prefix, StringComparison.Ordinal)) {
return true;
}
}
return false;
}
}
Approach 2: Two hash sets: words and prefixes
What's slow: the list forces every query to scan all stored words. A hash set would fix search, but startsWith still has no direct lookup.
The insight that fixes it: a prefix query is an exact lookup if you store every prefix. On insert, add the word to a words set and add each of its prefixes to a prefixes set. Both queries become one hash lookup.
The cost moves to insert. Each of the L prefixes is a new string of up to L characters, so you pay for building and hashing them.
Steps
- Create two empty hash sets,
wordsandprefixes, in the constructor. - In
insert, add the whole word towords. - In
insert, loopifrom 1 to the word length and add the firsticharacters toprefixes. - In
search, return whetherwordscontains the query. - In
startsWith, return whetherprefixescontains the query.
Dry run
Trace the example on an empty structure.
- Constructor:
words = {},prefixes = {}. search("a"):"a"is not inwords. Returnfalse.startsWith("a"):"a"is not inprefixes. Returnfalse.
The output is [null, false, false]. For comparison, insert("app") would put app in words and a, ap, app in prefixes. After that startsWith("ap") is a single lookup.
Complexity
| Time | O(L^2) insert, O(L) search and startsWith |
|---|---|
| Space | O(S), where S is the sum of L^2 over inserted words |
Let L be the length of the word being processed. Insert creates L prefix strings of lengths 1 to L, which totals L * (L + 1) / 2 characters, so O(L^2) time and space per new word. Search and startsWith hash one string of length L, which costs O(L) and is independent of how many words are stored. Shared prefixes are stored once in the set, but a worst case of all-distinct words still needs O(L^2) characters each.
PythonTested in our runner
from typing import List, Optional
class Trie:
def __init__(self):
self.words = set()
self.prefixes = set()
def insert(self, word: str) -> None:
self.words.add(word)
for i in range(1, len(word) + 1):
self.prefixes.add(word[:i])
def search(self, word: str) -> bool:
return word in self.words
def startsWith(self, prefix: str) -> bool:
return prefix in self.prefixes
JavaTested in our runner
import java.util.*;
class Trie {
private Set<String> words;
private Set<String> prefixes;
public Trie() {
words = new HashSet<>();
prefixes = new HashSet<>();
}
public void insert(String word) {
words.add(word);
for (int i = 1; i <= word.length(); i++) {
prefixes.add(word.substring(0, i));
}
}
public boolean search(String word) {
return words.contains(word);
}
public boolean startsWith(String prefix) {
return prefixes.contains(prefix);
}
}
C++Tested in our runner
#include <string>
#include <unordered_set>
using namespace std;
class Trie {
unordered_set<string> words;
unordered_set<string> prefixes;
public:
Trie() {
}
void insert(string word) {
words.insert(word);
for (size_t i = 1; i <= word.size(); i++) {
prefixes.insert(word.substr(0, i));
}
}
bool search(string word) {
return words.count(word) > 0;
}
bool startsWith(string prefix) {
return prefixes.count(prefix) > 0;
}
};
JavaScriptTested in our runner
var Trie = function() {
this.words = new Set();
this.prefixes = new Set();
};
/**
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
this.words.add(word);
for (let i = 1; i <= word.length; i++) {
this.prefixes.add(word.substring(0, i));
}
};
/**
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
return this.words.has(word);
};
/**
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
return this.prefixes.has(prefix);
};
GoTested in our runner
type Trie struct {
words map[string]bool
prefixes map[string]bool
}
func Constructor() Trie {
return Trie{
words: make(map[string]bool),
prefixes: make(map[string]bool),
}
}
func (this *Trie) insert(word string) {
this.words[word] = true
for i := 1; i <= len(word); i++ {
this.prefixes[word[:i]] = true
}
}
func (this *Trie) search(word string) bool {
return this.words[word]
}
func (this *Trie) startsWith(prefix string) bool {
return this.prefixes[prefix]
}
C#Tested in our runner
public class Trie {
private HashSet<string> words;
private HashSet<string> prefixes;
public Trie() {
words = new HashSet<string>();
prefixes = new HashSet<string>();
}
public void insert(string word) {
words.Add(word);
for (int i = 1; i <= word.Length; i++) {
prefixes.Add(word.Substring(0, i));
}
}
public bool search(string word) {
return words.Contains(word);
}
public bool startsWith(string prefix) {
return prefixes.Contains(prefix);
}
}

Solution pattern
Tries
Part of Design Patterns
Approach 3: Trie with 26 child slotsOptimalTries
What's slow: the two-set version stores a, ap, app, appl, apple as five separate strings. The prefix app is copied into every longer prefix, which costs O(L^2) per insert.
The insight that fixes it: store each character once, in a tree. A node represents one prefix, and its 26 child slots point to the node for that prefix plus one letter. Moving down one level appends one character, so no string is ever copied.
Each node also carries an isEnd flag. It is set on the node where an inserted word finishes. search needs the node to exist and the flag to be set. startsWith needs only the node to exist. A small helper that walks a string and returns the final node, or nothing, serves both queries.
Steps
- Define a node with
children, an array of 26 empty slots, and a booleanisEndset to false. - Create one root node in the constructor. It stands for the empty prefix.
- In
insert, start at the root. For each character, computec - 'a', create the child if the slot is empty, and move into it. - After the last character, set
isEnd = trueon the current node. - Write a helper
walk(s)that followssfrom the root and returns the last node, or nothing if a slot is empty. - In
search, return true whenwalk(word)finds a node and itsisEndis true. - In
startsWith, return true whenwalk(prefix)finds a node.
Dry run
Trace the example. The constructor creates only the root, and all 26 of its slots are empty.
| Step | Call | Position | Slot checked | Result |
|---|---|---|---|---|
| 1 | Trie() | root created | none | returns null |
| 2 | search("a") | start at root | root slot 0 (a) is empty | walk gives nothing, return false |
| 3 | startsWith("a") | start at root | root slot 0 (a) is empty | walk gives nothing, return false |
The output is [null, false, false].
For contrast, after insert("app") the root has a child at slot 0, that node has a child at slot 15 (p), and that node has a child at slot 15 again. The last node has isEnd = true. Then search("apple") reaches the last p node, finds slot 11 (l) empty, and returns false.
Complexity
| Time | O(L) per operation |
|---|---|
| Space | O(T * 26), where T is the total number of nodes created |
Let L be the length of the word or prefix passed to the call. Each operation visits one node per character and does constant work at each, so insert, search and startsWith all run in O(L). Cost does not depend on how many words are stored.
Each insert creates at most L new nodes, so T is at most the total characters inserted. Every node holds 26 slots, which gives O(26 * T) space. Shared prefixes reduce T below the raw character count.
PythonTested in our runner
from typing import List, Optional
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
i = ord(ch) - ord('a')
if node.children[i] is None:
node.children[i] = TrieNode()
node = node.children[i]
node.is_end = True
def _walk(self, s: str):
# Follow s from the root; return the last node or None.
node = self.root
for ch in s:
node = node.children[ord(ch) - ord('a')]
if node is None:
return None
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.is_end
def startsWith(self, prefix: str) -> bool:
return self._walk(prefix) is not None
JavaTested in our runner
import java.util.*;
class Trie {
private static class Node {
Node[] children = new Node[26];
boolean isEnd = false;
}
private Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
Node node = root;
for (int k = 0; k < word.length(); k++) {
int i = word.charAt(k) - 'a';
if (node.children[i] == null) {
node.children[i] = new Node();
}
node = node.children[i];
}
node.isEnd = true;
}
private Node walk(String s) {
Node node = root;
for (int k = 0; k < s.length(); k++) {
node = node.children[s.charAt(k) - 'a'];
if (node == null) {
return null;
}
}
return node;
}
public boolean search(String word) {
Node node = walk(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
return walk(prefix) != null;
}
}
C++Tested in our runner
#include <string>
using namespace std;
class Trie {
struct Node {
Node* children[26];
bool isEnd;
Node() : isEnd(false) {
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
}
};
Node* root;
Node* walk(const string& s) {
Node* node = root;
for (char c : s) {
node = node->children[c - 'a'];
if (node == nullptr) {
return nullptr;
}
}
return node;
}
public:
Trie() {
root = new Node();
}
void insert(string word) {
Node* node = root;
for (char c : word) {
int i = c - 'a';
if (node->children[i] == nullptr) {
node->children[i] = new Node();
}
node = node->children[i];
}
node->isEnd = true;
}
bool search(string word) {
Node* node = walk(word);
return node != nullptr && node->isEnd;
}
bool startsWith(string prefix) {
return walk(prefix) != nullptr;
}
};
JavaScriptTested in our runner
function makeNode() {
return { children: new Array(26).fill(null), isEnd: false };
}
var Trie = function() {
this.root = makeNode();
};
Trie.prototype.walk = function(s) {
let node = this.root;
for (let k = 0; k < s.length; k++) {
node = node.children[s.charCodeAt(k) - 97];
if (node === null) {
return null;
}
}
return node;
};
/**
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
let node = this.root;
for (let k = 0; k < word.length; k++) {
const i = word.charCodeAt(k) - 97;
if (node.children[i] === null) {
node.children[i] = makeNode();
}
node = node.children[i];
}
node.isEnd = true;
};
/**
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
const node = this.walk(word);
return node !== null && node.isEnd;
};
/**
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
return this.walk(prefix) !== null;
};
GoTested in our runner
type node struct {
children [26]*node
isEnd bool
}
type Trie struct {
root *node
}
func Constructor() Trie {
return Trie{root: &node{}}
}
func (this *Trie) walk(s string) *node {
cur := this.root
for i := 0; i < len(s); i++ {
cur = cur.children[s[i]-'a']
if cur == nil {
return nil
}
}
return cur
}
func (this *Trie) insert(word string) {
cur := this.root
for i := 0; i < len(word); i++ {
idx := word[i] - 'a'
if cur.children[idx] == nil {
cur.children[idx] = &node{}
}
cur = cur.children[idx]
}
cur.isEnd = true
}
func (this *Trie) search(word string) bool {
n := this.walk(word)
return n != nil && n.isEnd
}
func (this *Trie) startsWith(prefix string) bool {
return this.walk(prefix) != nil
}
C#Tested in our runner
public class Trie {
private class Node {
public Node[] Children = new Node[26];
public bool IsEnd = false;
}
private Node root;
public Trie() {
root = new Node();
}
private Node Walk(string s) {
Node node = root;
foreach (char c in s) {
node = node.Children[c - 'a'];
if (node == null) {
return null;
}
}
return node;
}
public void insert(string word) {
Node node = root;
foreach (char c in word) {
int i = c - 'a';
if (node.Children[i] == null) {
node.Children[i] = new Node();
}
node = node.Children[i];
}
node.IsEnd = true;
}
public bool search(string word) {
Node node = Walk(word);
return node != null && node.IsEnd;
}
public bool startsWith(string prefix) {
return Walk(prefix) != null;
}
}
Common mistakes
- Returning
truefromsearchas soon as the walk finishes, without readingisEnd. After inserting onlyapple,search("app")would wrongly pass. Returnnode != null && node.isEnd. - Forgetting to set
isEnd = trueafter the insert loop. Everysearchthen fails even for words you inserted. Set the flag on the final node, not on a node inside the loop. - Writing
node.children[i] = new Node()on every step ofinsert, even when the slot is filled. This wipes out the subtree below, so insertingcaraftercatlosescat. Create a child only when the slot is empty. - Indexing with
ord(ch)orcinstead ofc - 'a'. The array has 26 slots, so the index is out of range. Subtract the code ofaevery time. - Making
startsWithcheckisEnd. ThenstartsWith("app")fails when onlyappleexists. A prefix query needs only that the node exists. - Dereferencing a missing child in the walk, for example reading
node.children[i].children[j]without a null check. Test for an empty slot after every step and return early.
Edge cases
- Query before any insert (the verified example):
search("a")andstartsWith("a")both return false because the root has no children. - Insert
apple, thensearch("app")returns false andstartsWith("app")returns true. The prefix node exists but has no end flag. - Insert
appand thenapple. Bothsearch("app")andsearch("apple")return true, since the flag on theappnode survives. - Insert the same word twice. The second insert follows existing nodes and sets the same flag again, so nothing breaks.
- Query longer than any stored word: with only
appinserted,search("apple")andstartsWith("apple")both return false because thelslot is empty. - A single-character word of length 1 and a 2000-character word both work, since the loop is per character and has no recursion.
Follow-ups interviewers ask
- How would you add a delete operation?
- Walk to the word's final node and clear
isEnd. Then, going back up the path, remove each node that has no children and no end flag. You need a parent pointer, a recursive walk, or a stack of the path. That frees memory while keeping other words that share the prefix. - What if the alphabet is large, such as Unicode, and 26-slot arrays waste memory?
- Replace the child array with a hash map from character to node, created lazily. Each node then pays only for the children it has. Lookups stay O(1) on average, so the per-operation time is still O(L). The cost is a larger constant factor and less predictable memory layout.
- How would you return all words that start with a prefix, for autocomplete?
- Walk to the prefix node with the same helper. Then run a depth-first search from that node, building the string as you go and collecting it whenever you pass a node with
isEndset. The cost is O(L) for the walk plus the size of the subtree you visit.
Implement Trie (Prefix Tree) FAQ
What is the time complexity of Implement Trie (Prefix Tree)?
Insert, search and startsWith each take O(L), where L is the length of the word or prefix. The walk visits one node per character and does constant work per node. The number of stored words does not matter.
Why use a trie for Implement Trie (Prefix Tree)?
The prefix query is the reason. A trie stores shared beginnings once, so reaching the node for a prefix answers the question directly. A list needs a scan of all words, and a hash set has no way to ask about a beginning without storing every prefix.
What is the difference between a trie and a tree?
A tree is any connected structure of nodes with no cycles. A trie is a specific tree where each edge is labelled with a character and the path from the root spells a prefix. Its shape comes from the stored strings, and it is not sorted by node value like a binary search tree.
How do you implement a trie in Python?
Make a TrieNode with a children list of 26 slots, or a dict, and an is_end boolean. The Trie holds a root node. Insert walks the word and creates missing children, then sets is_end. A dict for children is shorter to write and works well when the alphabet is large.
Can Implement Trie (Prefix Tree) be solved in O(1) extra space?
No, if the structure must answer arbitrary queries later. The stored words have to live somewhere, so total memory grows with the input. Each individual search or startsWith can run with O(1) extra space, because the walk is iterative and keeps only one node pointer.
What is the difference between LeetCode 208 and the Trie II problem?
This problem only asks whether a word or prefix exists, so a boolean flag per node is enough. The Trie II variant counts how many times each word was inserted and supports erase. That needs a counter on each node in place of the flag, typically one for words ending there and one for words passing through.
Asked at
See which companies ask this — Pro
Related problems
- Design Add and Search Words Data Structure · same technique: Tries
- Extra Characters in a String · same technique: Tries
- Replace Words · same technique: Tries
- Design Search Autocomplete System · same technique: Tries
- Word Squares · same technique: Tries
- LRU Cache · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns
- Encode and Decode Strings · same pattern: Design Patterns
- Detect Squares · same pattern: Design Patterns