Skip to content

Tries

Tries in under a minute

A trie (prefix tree) stores words one character per node. Words that start the same way share the same path from the root, so “does anything start with this prefix?” is answered by walking the prefix and nothing else.

insert: car, card, care, cat, dog (* = a word ends here)
root
├─ c
│ └─ a
│ ├─ r* "car"
│ │ ├─ d* "card"
│ │ └─ e* "care"
│ └─ t* "cat"
└─ d
└─ o
└─ g* "dog"
  • The problem says prefix, autocomplete, or “starts with”.
  • You answer many queries against one fixed set of words.
  • You search a grid or text for many words at once and want to stop a path the moment no word starts that way (Word Search II).
  • A hash set can say “is this exact word stored?” in O(L) but cannot say “does any word start with this?” without scanning every word. A trie does both in O(L).
  • Cost: more memory than a set, since each node holds a child map.
class Node:
def __init__(self):
self.children = {} # char -> Node
self.is_word = False
def walk(root, s):
node = root
for ch in s:
if ch not in node.children:
return None # no stored word goes this way
node = node.children[ch]
return node # prefix exists; check node.is_word for a full word

Insert is the same walk, creating missing nodes and setting is_word at the end.