Algorithms Playbook
Data structureTime O(L) · Space O(total letters)7 min read

Tries: prefix trees for words

A tree where each edge is a letter, so words that share a prefix share a path. Autocomplete, spell checkers and word-search problems.

In short

A trie stores words letter by letter along a path from the root; words with a common prefix share nodes. Insert, search and prefix queries all cost O(L) for a word of length L, independent of how many words are stored.

Why not just a hash set?

A hash set answers "is this exact word stored?" in O(L). It can't answer "which words start with ca?" without scanning everything. A trie answers prefix questions by simply walking down.

Trie: insert words, check a prefix
Words
Prefix
Speed
·
1class Trie:
2 def __init__(self):
3 self.root = {}
4 def insert(self, word):
5 node = self.root
6 for ch in word:
7 node = node.setdefault(ch, {})
8 node["$"] = True
9 def starts_with(self, prefix):
10 node = self.root
11 for ch in prefix:
12 if ch not in node: return False
13 node = node[ch]
14 return True
A trie stores words letter by letter along a path from the root. Words that share a prefix share the same nodes.

Variables

words3
Step 1/16· Steps: 0
Every operation walks one node per letter: O(L) for a word of length L, no matter how many words are stored.

Operations

  • Insert: walk down, creating missing children, then mark the last node as the end of a word.
  • Search (whole word): walk down; succeed only if the last node is marked as a word end.
  • Starts with (prefix): walk down; succeed if the path exists, no end marker needed.
  • Autocomplete: walk to the prefix node, then DFS below it to list the words.
TrieHash set
Exact lookupO(L)O(L)
Prefix queryO(L)O(n·L) scanning
SpaceShared prefixes, but one node per letterOne entry per word
Sorted listingDFS visiting children in orderNeeds sorting

Key takeaways

  • 01A trie shares prefixes: one path per letter from the root.
  • 02Insert, search and prefix queries are O(L).
  • 03Mark word ends: "car" can be a prefix of "card".
  • 04Reach for a trie when the problem is about prefixes.

Check your understanding

1 of 3

What does a trie do better than a hash set?

Related topics