Skip to content

Trie Basics

Lesson 1 of 4 · 5 min

Trie Basics

Step 1 of 10

An empty trie is one root node. Every word starts its path here.

The Idea

A trie spells words out instead of storing them whole. Each edge carries one character, so the path down from the root is a prefix. Words that share a prefix share those nodes.

One flag per node marks "a word ends here" — without it you cannot tell the word car from the prefix inside cart.

Real-World Example

An old library card catalogue: drawers labelled A–C, inside them dividers for the second letter, then the third. Nobody stores the title twice because two books both start with "Ca" — you walk the labels and every book under that divider is a hit.

The Code

Your turn

What does this print?

root = {}
for word in ["do", "dorm"]:
  node = root
  for ch in word:
      node = node.setdefault(ch, {})
  node["$"] = True
print(sorted(root["d"]["o"]))

Mini quiz

1 / 3

What does one edge of a trie represent?