Sub topic 1
Why a trie? Sharing prefixes between strings
Prerequisites
This chapter assumes you know:
- Trees and depth-first traversal.
- Recursion.
- Hash maps (dictionaries) and arrays.
- Big-O notation.
- Basic string handling, such as indexing and iterating over characters.
The problem with storing strings as whole values
Suppose you keep a set of words: car, card, care, cat. A hash set answers "is card in the set?" quickly. It treats each word as one opaque value, though. It cannot answer "which words start with car?" without checking every word. A sorted array can answer prefix queries with binary search, but each comparison may scan many characters, and inserting a new word means shifting elements.
Look at the four words again. They all begin with ca, and three begin with car. A hash set or an array stores those shared letters again for every word. A trie avoids this repetition.
The idea: one path per string, shared where prefixes match
A trie (also called a prefix tree) is a tree that stores strings one character at a time. Each edge from a node to a child is labeled with a character. A word is spelled out by the edges along a path that starts at the root. Words that share a prefix share the first part of that path.
The root represents the empty string. Each node represents the prefix you get by reading the edge labels from the root down to that node.
The double circles mark nodes where a stored word ends. The tree has seven nodes besides the root for words that would take 3 + 4 + 4 + 3 = 14 characters if stored separately. Here only 6 nodes are needed below the root, since each shared letter appears once.
Why the end marker matters
Look at the node for car. It is on the path to card and care, yet car is also a word of its own. The path alone cannot tell you that. The node for ca is on a path too, but ca is not a word.
So each node carries a flag saying "a stored word ends here". Without it, a trie could only tell you that some word passes through a node, and it could not tell a stored word from a mere prefix of one. This flag is what separates an exact search from a prefix check. You will see both in the chapters on searching.
What this buys you
Following a string through a trie means taking one edge per character. The work depends on the length of the string, not on how many words are stored. Looking up card takes four steps whether the trie holds ten words or ten million.
Prefix queries also become natural. To ask whether any word starts with ca, walk two edges. If the walk succeeds, the answer is yes. Every word with that prefix lives in the subtree under the node you reached.
| Question | Hash set | Sorted array | Trie |
|---|---|---|---|
| Is this exact word stored? | Fast on average | Binary search | Walk one edge per character |
| Does any word start with this prefix? | Must check every word | Binary search for the first match | Walk one edge per character |
| List all words with a prefix | Must check every word | Binary search, then scan | Traverse the subtree |
The costs are covered precisely in a later chapter. For now, keep the shape of the idea: the structure of the data mirrors the structure of the strings.
A first look at the code
Here is the smallest useful version. Each node holds a dictionary of children and the end-of-word flag. Later chapters explain each method.
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
t = Trie()
for w in ["car", "card", "care", "cat"]:
t.insert(w)
print(sorted(t.root.children)) # ['c']
print(sorted(t.root.children["c"].children)) # ['a']The root has only one child, c, because every word starts with c. That is the sharing in action.
Exercise
You insert the words "to", "tea" and "ten" into an empty trie. How many nodes exist below the root, and which nodes are marked as word ends?
Show answer
There are 5 nodes below the root: t, to, te, tea and ten. The word-end nodes are to, tea and ten. The node te is not marked, because "te" was never inserted.