Skip to content

Lesson 17 of 40Trees and graphs

Tries

Build a prefix tree that answers "is this a word?" and "does anything start with this?" in time set by word length.

22 min read0/6 questions

Type "pyt" into a search box and you instantly see "python", "pytest", "pytorch". The suggestions do not come from scanning every word in a dictionary. They come from a trie (say "try"), a tree built so that every word sharing a prefix shares a path.

Tries show up in autocomplete, spell checkers, IP routing tables, and in interview problems like word search and "replace words with their root". Once you can build one, those problems become a walk down a tree.

One letter per step

A trie stores words character by character. The root is empty. Each link out of a node is one letter, so the path from the root to any node spells a prefix. A node also carries a flag, usually called is_end, that says "a complete word stops here".

Here is a trie holding car, cart, cat and dog. To make it readable, each node is labelled with the prefix its path spells. Nodes marked word have is_end = True.

Trie for car, cart, cat, dog
(root)cartwordcarwordcatwordcacdogworddodroot

Every lookup starts at the empty root.

1/5

Notice what the work depends on. Looking up cart takes four steps whether the trie holds four words or four million. The cost is set by the length of the word, not the number of words.

Quick check
Why does each node need an is_end flag? Why not just check that the path exists?
Need a nudge? A hint rules out a wrong answer.

The code

A node is a map of children plus the flag. Insert walks down, creating missing children. Search and prefix check share one walk.

Python
class TrieNode: def __init__(self): self.children = {} # letter -> TrieNode self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end = True def _walk(self, text): node = self.root for ch in text: if ch not in node.children: return None node = node.children[ch] return node def search(self, word): node = self._walk(word) return node is not None and node.is_end def starts_with(self, prefix): return self._walk(prefix) is not None t = Trie()for w in ["car", "cart", "cat", "dog"]: t.insert(w)print(t.search("car"), t.search("ca"), t.starts_with("ca"), t.search("dot"))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

t = Trie()
t.insert("app")
t.insert("apple")
print(t.search("appl"), t.starts_with("appl"), t.search("app"))
Need a nudge? Hints walk you through it.

Autocomplete: collect everything below a node

To suggest completions for a prefix, walk to the prefix node, then do a depth-first search from there, collecting every node with is_end set. The path you took spells each word.

def complete(trie, prefix):
    node = trie._walk(prefix)
    if node is None:
        return []
    words = []
    def dfs(n, path):
        if n.is_end:
            words.append(path)
        for ch, child in sorted(n.children.items()):
            dfs(child, path + ch)
    dfs(node, prefix)
    return words
 
# complete(t, "ca") -> ['car', 'cart', 'cat']

A production autocomplete also stores a popularity count on each word end and keeps only the top few per node, so it does not have to explore a huge subtree on every keystroke.

Put it in order4 steps

Put the autocomplete steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Cost and the memory tradeoff

Let L be the length of the word or prefix.

OperationTimeWhy
insert(word)O(L)One step per letter
search(word)O(L)One step per letter, then check the flag
starts_with(prefix)O(L)Same walk, no flag check
Build from n wordsO(total letters)Each letter inserted once

Compare with a plain set of words. word in my_set is also about O(L) (it has to hash the string), so for exact lookups a set is simpler and just as fast. The trie wins when the question is about prefixes: "does anything start with pre?" on a set means checking every word.

The price is memory. Each node is an object with its own dictionary, which in Python is a few hundred bytes. A trie of 100,000 English words can have several hundred thousand nodes. Shared prefixes help, but a trie usually uses more memory than the raw strings. Two common fixes: store children in a fixed array of 26 slots when the alphabet is small, or compress chains of single-child nodes into one node (a radix tree).

Quick check
Which task is a trie clearly better at than a hash set of the same words?
Need a nudge? A hint rules out a wrong answer.

Wildcard search: Add and Search Words

A common follow-up: search must accept . as "any one letter", so .ad matches bad, dad and mad. Exact letters still walk one child. A dot has to try every child at that depth, which turns the walk into a depth-first search. Each branch either fails fast (the letter is missing) or reaches the end of the pattern and checks the end flag.

This version stores nodes as plain dicts with a "$" key as the end marker, a compact style you will see in many interview answers. The idea is the same as TrieNode.

Python
class WordDictionary: def __init__(self): self.root = {} def add_word(self, word): node = self.root for ch in word: node = node.setdefault(ch, {}) node["$"] = True # end marker def search(self, word): def match(node, i): if i == len(word): return "$" in node ch = word[i] if ch == ".": # try every child, skip the marker return any(match(child, i + 1) for key, child in node.items() if key != "$") return ch in node and match(node[ch], i + 1) return match(self.root, 0) d = WordDictionary()for w in ["bad", "dad", "mad"]: d.add_word(w)assert d.search("pad") is Falseassert d.search("bad") is Trueassert d.search("...") is Trueassert d.search("....") is Falseprint(d.search(".ad"), d.search("b.."), d.search("b."))
Output
Press Run (⌘ Enter) to see what happens.

Cost: with no dots it is still O(L). Each dot multiplies the work by up to the alphabet size, so a pattern of all dots can visit every node at that depth: O(26^L) in the worst case, bounded by the size of the trie. Interviewers ask this. The honest answer is "O(L) for plain words, and up to the whole trie for patterns full of dots". Two details matter in the code: skip the "$" marker when iterating children (it is not a letter), and use any, which stops at the first match instead of exploring every branch.

Word Search II: trie plus backtracking

Given a letter grid and a list of words, return every word that can be traced through adjacent cells without reusing a cell. The naive approach runs the single-word grid search from Backtracking once per word. With 10,000 words, that is 10,000 full grid searches, and most of them retrace the same prefixes.

Build a trie of the words instead and run one DFS from each cell, walking the grid and the trie together. If the grid letter is not a child of the current trie node, no word continues that way, so the branch dies at once. One walk checks every word at the same time.

Three refinements make it fast enough for the large test cases:

  • Store the word at its end node (node.word = "oath") instead of rebuilding the string from the path.
  • Clear it once found (node.word = None), so a word that appears twice in the grid is reported once.
  • Prune emptied branches. After exploring from a node, if it has no children and no word left, delete it from its parent. Later searches never walk into a part of the trie that has nothing left to find. On boards with many matches this is the difference between passing and timing out.
Python
class Node: def __init__(self): self.children = {} self.word = None # the full word stored at its end node def find_words(board, words): root = Node() for w in words: node = root for ch in w: node = node.children.setdefault(ch, Node()) node.word = w rows, cols = len(board), len(board[0]) found = [] def dfs(r, c, parent): ch = board[r][c] node = parent.children.get(ch) if node is None: return # no word continues this way if node.word is not None: found.append(node.word) node.word = None # report each word once board[r][c] = "#" # mark as used on this path for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#": dfs(nr, nc, node) board[r][c] = ch # un-mark on the way back if not node.children and node.word is None: del parent.children[ch] # prune: nothing left to find below for r in range(rows): for c in range(cols): dfs(r, c, root) return found board = [list("oaan"), list("etae"), list("ihkr"), list("iflv")]res = find_words(board, ["oath", "pea", "eat", "rain"])assert sorted(res) == ["eat", "oath"]assert board == [list("oaan"), list("etae"), list("ihkr"), list("iflv")] # restoredassert sorted(find_words([list("ab")], ["ab", "ba", "abc", "a"])) == ["a", "ab", "ba"]print(sorted(res))
Output
Press Run (⌘ Enter) to see what happens.

The # marking and the restore after the loop are the grid version of choose and un-choose, covered in Backtracking. The second assert checks that the board is left exactly as it was given, which an interviewer may ask about: callers rarely expect a search to change their data.

Quick check
In Word Search II, why delete a trie node from its parent once it has no children and no word left?
Need a nudge? A hint rules out a wrong answer.

Deleting a word and cleaning up

delete looks simple: walk to the end node and set is_end = False. That is correct, and many production tries do only that. But it leaves dead nodes behind. Delete cart and the t node stays, holding no word and leading nowhere. A trie that sees many inserts and deletes (a cache of active session keys, say) slowly fills with dead branches.

The full delete removes nodes on the way back up, but only while each node is both not a word end and has no remaining children. Recursion fits, because the decision for each node depends on what happened below it.

Python
class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end = True def count_nodes(self): stack, n = [self.root], 0 while stack: node = stack.pop(); n += 1 stack.extend(node.children.values()) return n def delete(self, word): def go(node, i): # returns True if the caller should remove its link to this node if i == len(word): if not node.is_end: return False # word was never stored node.is_end = False else: child = node.children.get(word[i]) if child is None or not go(child, i + 1): return False del node.children[word[i]] return not node.is_end and not node.children go(self.root, 0) t = Trie()for w in ["car", "cart", "cat"]: t.insert(w)sizes = [t.count_nodes()]for w in ["cart", "ca", "car", "cat"]: t.delete(w) sizes.append(t.count_nodes())print(sizes)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

The trie starts with car, cart and cat, and the root counts as a node. What does the block above print?

print(sizes)
Need a nudge? Hints walk you through it.

A Python dict that loses its keys does not shrink its internal table straight away, so the memory win from deleting nodes comes from dropping whole node objects, not from emptying their dicts.

Children as a dict or as a 26-slot array

The node shape is a real design choice, and interviewers like to hear you weigh it.

Dict / Map of childrenFixed array of 26
Find a childHash the letter, then look upchildren[ord(ch) - 97], one index
Memory per nodeGrows with the number of childrenAlways 26 slots, mostly empty deep in the trie
AlphabetAny: Unicode, digits, URL path partsMust be small and known up front
Iterate children in orderSort the keysAlready in alphabetical order

Most trie nodes, especially deep ones, have one or two children. So for a large dictionary the array wastes most of its slots, and the dict usually wins on memory. The array wins on speed for small fixed alphabets and gives sorted iteration for free, which is handy for autocomplete. In a lower-level language the array of pointers costs eight bytes per slot on a 64-bit machine even when empty, so 26 slots is roughly 200 bytes of mostly nothing per node. In Python, each node is an object either way, so the gap is smaller than you might guess. Measure with your own data before deciding. If memory really matters, the bigger win is structural: a radix tree, or a sorted array of strings searched with binary search.

Binary tries: Maximum XOR of Two Numbers

A trie does not have to hold letters. Store each number as its bits, highest bit first, and each node has at most two children: 0 and 1. This binary trie solves "find the maximum a ^ b over all pairs" in O(n · bits) instead of O(n²).

The greedy idea comes from Bit Manipulation's rule that XOR is 1 where bits differ. The highest bit matters most: getting a 1 at bit 30 beats any combination of lower bits. So for each number x, walk down the trie and at every level try to go to the opposite bit of x. If that child exists, this bit of the XOR is 1. If not, you are forced along the same bit and this XOR bit is 0.

Binary trie of 2 (010), 5 (101), 7 (111), querying x = 2
(root)01020101015101117111root

The trie holds 2, 5 and 7 as 3-bit numbers. Find the best partner for x = 2, which is 010.

1/4
Python
def find_maximum_xor(nums, bits=31): root = {} for x in nums: # insert each number, high bit first node = root for b in range(bits - 1, -1, -1): node = node.setdefault((x >> b) & 1, {}) best = 0 for x in nums: node, cur = root, 0 for b in range(bits - 1, -1, -1): bit = (x >> b) & 1 want = 1 - bit # the opposite bit makes this XOR bit 1 if want in node: cur |= 1 << b node = node[want] else: node = node[bit] # forced: only the same bit exists best = max(best, cur) return best assert find_maximum_xor([2, 5, 7], bits=3) == 7assert find_maximum_xor([0]) == 0print(find_maximum_xor([3, 10, 5, 25, 2, 8]))
Output
Press Run (⌘ Enter) to see what happens.

bits=31 covers non-negative 32-bit integers. The else branch never fails: every stored number has a path of full length, so if the opposite child is missing, the same-bit child must exist. Binary tries also answer "maximum XOR with an element no larger than m" (sort the queries and insert numbers as you go) and appear in routing tables, where IP prefixes are stored bit by bit and a lookup finds the longest matching prefix.

How to recognise it

Common mistakes:

  • Forgetting is_end, so every prefix counts as a word.
  • Marking only leaves as word ends. car must be marked even though cart continues below it.
  • Creating new nodes during search. Lookups must never change the trie; use a read-only walk.
  • Using a trie when a set would do. If nothing in the problem mentions prefixes, a set is simpler.
ChallengeMedium

Implement a Trie

Build a prefix tree (trie) that stores lowercase words.

It needs three methods:

  • insert(word) adds a word.
  • search(word) returns True / true only if that exact word was inserted.
  • starts_with(prefix) (Python) / startsWith(prefix) (TypeScript) returns whether any inserted word begins with prefix.
t = Trie()
t.insert("car")
t.search("car")      → True
t.search("ca")       → False   ("ca" is only a prefix)
t.starts_with("ca")  → True
t.insert("ca")
t.search("ca")       → True

Every method should run in O(length of the word), whatever the number of words stored.

class Trie: def __init__(self) -> None: # Each node needs its children and a flag saying "a word ends here". pass def insert(self, word: str) -> None: pass def search(self, word: str) -> bool: pass def starts_with(self, prefix: str) -> bool: pass
Key terms
trie
A tree where each link is one character and each root-to-node path spells a prefix.
is_end flag
Marks that a complete inserted word ends at this node, so prefixes are not mistaken for words.
O(L) lookup
Trie operations cost one step per character of the word, independent of how many words are stored.
prefix query
A question like "does any word start with abc?" A trie answers it by walking to the prefix node.
radix tree
A compressed trie where chains of single-child nodes are merged to save memory.
wildcard search
A trie lookup where . matches any letter, so the walk branches into a DFS over every child at that depth.
trie pruning
Deleting a trie node once nothing is left to find below it, so later searches stop early. Key to Word Search II.
binary trie
A trie over the bits of numbers, high bit first, with at most two children per node. Finds maximum XOR greedily.