LeetCode #208 Medium

Implement Trie (Prefix Tree)

Implement Trie (Prefix Tree) is LeetCode 208 (Medium). Build a class Trie with three methods:

  • insert(word) stores a word.
  • search(word) returns true only if that exact word was inserted.
  • startsWith(prefix) returns true if any inserted word begins with prefix.

All strings are lowercase letters, up to 2,000 long, and there are at most 3 × 10⁴ calls in total.

Constraints
  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 * 10⁴ calls in total will be made to insert, search, and startsWith.
triedesignstring
Open on LeetCode ↗
02

Intuition

Store each word one letter per level, so words that begin the same way share the same path. Every node then stands for a prefix: the letters on the way down from the root to it. A node needs two things:

  • Children: a map (or a 26-slot array) from the next letter to the child node.
  • End flag: a boolean saying that a whole word stops at this node.

Walking a string from the root takes one step per letter, however many words are stored. startsWith only needs that walk to succeed. search also needs the end flag, because the path for "an" exists inside "ant" even if "an" itself was never inserted.

How to spot this pattern

Reach for a trie when the questions are about prefixes rather than whole strings: autocomplete, spell checkers, Word Search II, Replace Words. A hash set answers "is this exact word stored?" but has no fast way to answer "does any stored word start with this?".

03

Approach

Try it first

Before reading on, insert "ant" into an empty trie, then call search("an") and startsWith("an"). What does each return, and which single piece of data tells them apart? Aim for O(L) per call, where L is the length of the string.

1

Give each node children and an end flag

A node holds children, mapping a letter to the next node, and is_end, false by default. The root stands for the empty prefix. The C++ and Java versions use a 26-slot array instead of a map, which works because the input is only lowercase letters.

2

Insert: walk down, creating missing nodes

Start at the root. For each letter, create the child only if it is missing, then step into it. After the last letter, set is_end = True on that node, because the path alone cannot say whether a word ends here or a longer word just passes through.

3

Share one walk for both queries

_find(s) follows the letters of s from the root and returns the node it reaches, or None the moment a child is missing. A missing child means no stored word starts with that many letters of s, so there is no point reading further.

4

search checks the flag, startsWith does not

search returns true only if _find reached a node and that node has is_end set. startsWith returns true whenever _find reached a node, since every node in the trie lies on the path of at least one inserted word.

04

Code in Python, C++ and Java

▶1class TrieNode:
▶2 def __init__(self):
▶3 self.children = {}
▶4 self.is_end = False
▶5 
▶6 
▶7class Trie:
▶8 def __init__(self):
▶9 self.root = TrieNode()
▶10 
▶11 def insert(self, word):
▶12 node = self.root
▶13 for ch in word:
▶14 if ch not in node.children:
▶15 node.children[ch] = TrieNode()
▶16 node = node.children[ch]
▶17 node.is_end = True
▶18 
▶19 def _find(self, s):
▶20 node = self.root
▶21 for ch in s:
▶22 if ch not in node.children:
▶23 return None
▶24 node = node.children[ch]
▶25 return node
▶26 
▶27 def search(self, word):
▶28 node = self._find(word)
▶29 return node is not None and node.is_end
▶30 
▶31 def startsWith(self, prefix):
▶32 return self._find(prefix) is not None
rootword ends hereempty trie: only the root
root{}no children yet
The trie starts as a single root node with no children. Each later node stands for one prefix: the letters on the path from the root down to it.
rootaword ends hereinsertantno 'a' child → create it
ch'a'
prefix"a"new node
The node for the root has no child for 'a', so create one and step into it. The new node now stands for the prefix "a".
rootanword ends hereinsertantno 'n' child → create it
ch'n'
prefix"an"new node
The node for "a" has no child for 'n', so create one and step into it. The new node now stands for the prefix "an".
rootantword ends hereinsertantno 't' child → create it
ch't'
prefix"ant"new node
The node for "an" has no child for 't', so create one and step into it. The new node now stands for the prefix "ant".
rootantword ends hereinsertantmark the end of "ant"
is_endTrueat "ant"
All letters are placed. Set is_end on the last node (the green ring): it records that a whole word stops here, not just that some longer word passes through.
rootantword ends heresearchan'a' found → move down
ch'a'
node"a"prefix so far
A child for 'a' exists, so follow it. Every letter matched so far means some stored word begins with "a".
rootantword ends heresearchan'n' found → move down
ch'n'
node"an"prefix so far
A child for 'n' exists, so follow it. Every letter matched so far means some stored word begins with "an".
rootantword ends heresearchanno end mark on "an" → false
is_endFalse
returnFalse
The path for "an" exists, but only as part of a longer word: the last node has no end flag. So search returns false, even though startsWith would say true.
rootantword ends herestartsWithan'a' found → move down
ch'a'
node"a"prefix so far
A child for 'a' exists, so follow it. Every letter matched so far means some stored word begins with "a".
rootantword ends herestartsWithan'n' found → move down
ch'n'
node"an"prefix so far
A child for 'n' exists, so follow it. Every letter matched so far means some stored word begins with "an".
rootantword ends herestartsWithanpath exists → true
returnTrue
Every letter of "an" was found, so at least one stored word starts with it. startsWith ignores the end flag: reaching the node is enough.
rootantword ends hereinsertan'a' exists → reuse it
ch'a'
prefix"a"already stored
A child for 'a' is already there, because an earlier word starts with "a". Reuse it instead of making a copy: shared prefixes are stored once.
rootantword ends hereinsertan'n' exists → reuse it
ch'n'
prefix"an"already stored
A child for 'n' is already there, because an earlier word starts with "an". Reuse it instead of making a copy: shared prefixes are stored once.
rootantword ends hereinsertanmark the end of "an"
is_endTrueat "an"
All letters are placed. Set is_end on the last node (the green ring): it records that a whole word stops here, not just that some longer word passes through.
rootantword ends heresearchan'a' found → move down
ch'a'
node"a"prefix so far
A child for 'a' exists, so follow it. Every letter matched so far means some stored word begins with "a".
rootantword ends heresearchan'n' found → move down
ch'n'
node"an"prefix so far
A child for 'n' exists, so follow it. Every letter matched so far means some stored word begins with "an".
rootantword ends heresearchan"an" has the end mark → true
is_endTrue
returnTrue
The path exists and the last node has the end flag, so "an" was inserted as a whole word.
05

Common pitfalls

search that ignores the end flag

✗ Wrong
def search(self, word):
    return self._find(word) is not None
✓ Right
def search(self, word):
    node = self._find(word)
    return node is not None and node.is_end

This is startsWith under another name. After insert("apple"), search("app") returns true, because the nodes for "app" exist inside "apple".

Setting the end flag inside the loop

✗ Wrong
for ch in word:
    ...
    node = node.children[ch]
    node.is_end = True
✓ Right
for ch in word:
    ...
    node = node.children[ch]
node.is_end = True

Every prefix of the word gets marked as a word. After insert("apple"), search("a") and search("app") both return true. Only the node after the last letter should be marked.

Creating a child even when it exists (array version)

✗ Wrong
node.children[c] = new Node();
node = node.children[c];
✓ Right
if (node.children[c] == null) node.children[c] = new Node();
node = node.children[c];

The new node replaces the old one and everything below it. Insert "ant" then "an", and the t node is thrown away, so search("ant") returns false.

06

Edge cases

Inserting a word that is a prefix of a stored word

Inserting "an" after "ant" creates no nodes: every letter already exists, so only the flag on the n node changes.

Inserting the same word twice

The walk reuses every node and the flag is already true, so the trie is unchanged.

startsWith called with a whole stored word

A word counts as a prefix of itself, so startsWith("ant") returns true after insert("ant").

07

Complexity

Time
O(L) per call
Space
O(total letters inserted)
L is the length of the word or prefix. Trie insert, search and startsWith each do one child lookup per letter, no matter how many words are stored. Each inserted letter creates at most one node, so memory is bounded by the total length of all inserted words, and shared prefixes use less.
08

Implement Trie (Prefix Tree) FAQ

Hash map or 26-slot array for the children?

The array gives a direct index with no hashing, but every node pays for 26 slots even when it has one child. A map stores only the letters that exist and works for any alphabet. With lowercase-only input both pass; the array is usually faster and the map smaller on sparse tries.

Why not just keep the words in a hash set?

A set handles search well, but startsWith would have to check every stored word: up to 3 × 10⁴ words of up to 2,000 letters, on every call. Putting every prefix into a second set makes it fast but stores up to 2,000 strings for a single 2,000-letter word, which is O(L²) memory.

How do you delete a word from a trie?

Walk to the word's last node and clear is_end. To free memory as well, remove nodes on the way back up while they have no children and no end flag. Implement Trie II (problem 1804) asks for this, with counts stored at each node.