Lesson 3 of 3
Tries
A trie stores words as paths of letters that hang from one root, so words that start alike share their first nodes. Insert, search and starts-with each walk one letter per step, and a wildcard search tries every branch, depth first.
Draw the trie for a few words and count its nodes
Insert words into a dict-of-dicts trie, creating only the letters that are missing
Tell a whole-word search from a prefix check by the end-of-word mark
Write the same trie as a
TrieNodeclass withchildrenandis_endMatch a pattern with wildcard dots by trying every child, depth first
List every stored word that starts with a prefix
Your team's data catalog has a search box. Type ord and it offers orders, order_items and orders_daily: every table whose name starts with what you typed. It asks that question again at every keystroke, against tens of thousands of names.
A set answers the wrong question. "orders" in names finds a whole name with one hash lookup. But a set has no shortcut for "which names start with ord?". You have to ask every name, name.startswith("ord"), so each question costs one check per stored name. That is the brute force, and an interviewer expects you to name it first.
This lesson builds the structure made for prefix questions: the trie. Words that start alike share storage, so a prefix question follows one letter per step and never scans the stored words one by one.
A tree of letters
What shape lets "cat" and "car" share their first two letters? Store each word as a path down a tree, one letter per step. The top node is the root: it holds no letter and stands for the start, before any letter is read. Every other node holds one letter. A node's children are the nodes one step below it, one for each letter that can come next in some stored word. So a node can have many children, where a node in a binary tree or a heap has at most two.
The path root, c, a, t spells "cat", and the path root, c, a, r spells "car". Both paths run through the same nodes for c and a, so the shared start is stored once. This tree is a trie (the name comes from retrieval; most people say "try", so it does not sound like "tree"), also called a prefix tree.
A prefix of a word is a piece taken from its start: "c", "ca" and "cat" are prefixes of "cat". Every node stands for one prefix: the letters on the path from the root down to it. The root stands for the empty prefix, "", with no letters at all. "The node for 'ca'" means the node you reach by following c, then a.
A node also needs an end-of-word mark. Store "cart" alone, and the node for "car" exists, because "cart" passes through it. But "car" was never stored. So a node that exists proves only that some stored word starts that way, and each node carries a mark that says "a stored word ends here".
The widget below inserts four words one letter per step, then looks up the prefix "ca". The lime ring is the end-of-word mark. Above the drawing, a strip shows the word going in, with each letter tagged "new" (a node was added) or "reuse" (the node was already there). The readouts count letter nodes (the root is not counted), stored words, and the words that start with the prefix. The four words have 13 letters in all. Before you press Next, guess how many letter nodes they need.
Count the nodes yourself before we write any code.
Insert "car", "card", "care" and "cat" into an empty trie, in that order. How many letter nodes does the trie have? Do not count the root. Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Insert: follow the letters, add what is missing
How does a trie look in Python? Each node is a dict from a letter to the child node, and each child is another dict, so the whole trie is a dict of dicts. The root starts as an empty dict. The end mark is one more key, "$", with the value True. Any key that can never be a letter would do; $ means "end of the text" in regular expressions, so it reads as "end" at a glance. After inserting "cat" alone, the trie is {"c": {"a": {"t": {"$": True}}}}.
To insert a word, walk its letters from the root. For each letter, step down to that child, creating it first if it is missing. When the letters run out, put the end mark on the node you stand on. Before you step through, guess: once "cat" is in, how many new dicts does inserting "car" create?
def build(words):root = {}for word in words:node = rootfor ch in word:if ch not in node:node[ch] = {}node = node[ch]node["$"] = Truereturn root
(nothing printed yet)Insert never compares the new word with the stored ones. It does one dict check per letter and makes at most one new dict per letter, so inserting a word of L letters costs O(L), whether the trie holds 2 words or 2 million. Python's node = node.setdefault(ch, {}) does lines 6 to 8 in one line: setdefault returns the child for ch, adding an empty dict first if it is missing. Write the plain version until it comes without thinking.
Now read the nested dicts yourself. The second word here is shorter than the first.
This is the build function from the trace. Type exactly what the last line prints. Python prints a dict with single quotes, and a new key goes after the keys already in its dict.
def build(words):
root = {}
for word in words:
node = root
for ch in word:
if ch not in node:
node[ch] = {}
node = node[ch]
node["$"] = True
return root
print(build(["tea", "te"]))
Search and starts-with: follow the letters
What can we ask once the words are in? Two questions, and one walk answers both. starts_with(prefix) asks whether some stored word begins with prefix. search(word) asks whether word itself was stored. Both follow the letters from the root, and a missing child ends the walk with no. If every letter is found, we stand on the node for the text. Then starts_with only needs that node to exist, and search also needs the end mark there.
The trace writes the walk once, as follow, which returns the node for a text, or None when a letter is missing. The trie is typed in directly this time; it holds "cat" and "car". Before you step through, guess the four values the two print lines show.
def follow(root, text):node = rootfor ch in text:if ch not in node:return Nonenode = node[ch]return nodedef starts_with(root, prefix):return follow(root, prefix) is not Nonedef search(root, word):node = follow(root, word)return node is not None and "$" in noderoot = {"c": {"a": {"t": {"$": True}, "r": {"$": True}}}}print(starts_with(root, "ca"), search(root, "ca"))print(search(root, "car"), starts_with(root, "cow"))
(nothing printed yet)The end mark is the whole difference between the two questions. The node for "ca" exists because two words pass through it, so the prefix check says yes. No word ends there, so the whole-word check says no. Leave the mark out and see what breaks:
A teammate leaves out the end mark and writes search with the follow function from the trace:
def search(root, word):
return follow(root, word) is not None
The trie holds one word, "cart". What does search(root, "car") return?
Choose one answer, then check.
Here are the four answers for the trie and its three operations:
Recap: a trie stores each word as a path of letters from the root, sharing common starts. Insert creates the missing letters and marks the last node. Search and starts-with follow the letters and stop at a missing one. Starts-with needs only the node; search also needs the mark. Each costs O(L).
The same trie as a class
Why write a class, when nested dicts already work? The dict version mixes the end mark in with the letters. In the exercise above, the dict for "te" holds both 'a' and '$', so every loop over a node's keys has to remember to skip the mark. A small class gives the two parts their own names. The problems in this lesson use it:
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # True if a stored word ends here
As with ListNode in module 7, writing TrieNode() makes a new node and runs __init__ on it, with self naming that new node. children is the dict from before without the end mark, and is_end is the end mark. Every move of the dict version has a twin:
| Dict of dicts | TrieNode class |
|---|---|
a new node: {} | TrieNode() |
ch not in node | ch not in node.children |
node = node[ch] | node = node.children[ch] |
node["$"] = True | node.is_end = True |
"$" in node | node.is_end |
Now put insert together in the class version. The lines are here, out of order.
Put the lines in order to build insert(root, word) for the class version. root is a TrieNode, and TrieNode is already defined:
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # True if a stored word ends here
Indentation is part of each line. Two lines do not belong.
Add lines from the list below, in order.
node = node.children[ch]node.children[ch] = TrieNode()def insert(root, word):node = rootnode.is_end = Truenode = node.children[ch]node.is_end = Truefor ch in word:if ch not in node.children:
The problem wraps the root in a class Trie with insert, search and starts_with as methods. search and starts_with walk the same way, so write that walk once, as a helper method that returns the node for a text or None, and let both methods call it.
The speed test is where the brute force falls over. It stores 14,000 words, then asks 14,000 prefix questions of 4 letters each. The trie follows at most 4 letters per question. The set version asks every stored word each time, and most questions find no match, so that comes to close to 200 million checks. Watch also for "team" then "tea": the second insert makes no node at all. It only sets is_end on a node that "team" already made.
A dot matches any letter
What if the search does not know every letter? The second problem stores words and checks patterns. A pattern is made of letters and dots, and a dot matches any one letter: "c.t" matches "cat" and "cot", but not "ct" or "cart". The whole stored word must match: same length, letter for letter.
A letter has one child to follow. A dot could be any child, and we cannot tell in advance which one leads to a match. So we try them in turn: go down one child, and if the rest of the pattern fails below it, come back and try the next. This is depth-first search: go as deep as possible along one branch, then back up. Module 8 walked trees this way, and recursion keeps our place again: each call remembers which node it stands on and which pattern character comes next.
matches(node, pattern, i) answers one question: can pattern[i:] be spelled starting below node, ending at a stored word? It has three cases:
- The pattern is used up (
i == len(pattern)): the answer is whether a word ends atnode. - A letter: follow its one child, or return False if it is missing.
- A dot: try every child. Return True as soon as one child matches the rest, and return False only after every child has failed.
The dot's loop is for letter, child in node.items():, which hands out each key of the dict with its value: a letter and its child node. In the dict version, the dot's loop must skip the "$" key, whose value is True, not a node. The trie below holds "cat" and "dog", and the pattern is "..g": two dots, then the letter g. The arrow under pattern shows i, the next character to match. Before you step through, guess which calls return False, and how many calls to matches run in all, counting the first one.
def matches(node, pattern, i):if i == len(pattern):return "$" in nodech = pattern[i]if ch == ".":for letter, child in node.items():if letter != "$" and matches(child, pattern, i + 1):return Truereturn Falseif ch not in node:return Falsereturn matches(node[ch], pattern, i + 1)root = {"c": {"a": {"t": {"$": True}}}, "d": {"o": {"g": {"$": True}}}}
(nothing printed yet)The early True and the late False are the whole algorithm, and the trace showed both. Returning True the moment one branch matches is safe, because one stored word is enough. Returning False is safe only after the loop ends, because a branch we have not tried yet may still match.
One misplaced return turns this into a different algorithm. See what it does before you write the problem:
This version of the dot case returns inside the loop:
if ch == ".":
for letter, child in node.items():
if letter != "$":
return matches(child, pattern, i + 1)
return False
The rest of matches is as in the trace. With the same trie ("cat" and "dog"), what does matches(root, ".og", 0) return?
Choose one answer, then check.
Now trace a pattern on paper, the way you would at a whiteboard with no run button.
The trie holds "bad", "bat" and "cab", inserted in that order. On paper, trace matches(root, ".a", 0) with the function from the trace. Write each call as the prefix of the node it stands on and its i, in the order the calls start. How many calls run in all, counting the first one? What does the first call return?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The problem asks for the class version. There, node.children holds only letters, so the dot's loop needs no skip: it runs over node.children.values(), and the end check is node.is_end. You can also write matches inside search: then it reads pattern from there and needs only node and i.
Two things to keep from it. First, the problem's limit of 2 dots per pattern is what keeps the search fast: a search follows at most 26 × 26 = 676 paths, however many words are stored. Second, a dot never matches zero letters, because it always steps down to a child. With only "ab" stored, "ab." fails: the node for "ab" has no children, so the dot has nothing to try.
The same depth-first walk answers the search box from the start of the lesson. To list every word with a given prefix, follow the prefix to its node. Then visit every node in the branch below it, the way a dot visits every child, and collect each word whose end you meet. Write it for the class version:
Write words_with_prefix(root, prefix), which returns every stored word that starts with prefix, as a sorted list, or [] when there is none. A stored word starts with itself, and the empty prefix "" starts every word. The cell already has TrieNode and build(words), the class version of this lesson's insert: keep them as they are. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.Counting the words with a prefix needs no walk below it. Give each node a count, and let every insert add 1 to the count of each node on its path, the root included. Then the number of inserted words that start with a prefix is the count on the prefix's node: O(P) for a prefix of P letters. With "cat", "car" and "cart" inserted, the node for "ca" holds 3 and the node for "car" holds 2. If a word inserted twice should count once, call search first and skip the insert when the word is already stored.
Recap: a dot is a choice, so the search becomes depth first: try each child, return True on the first match, and return False only when every child has failed. Collecting every word below a node is the same walk without the early stop. The practice bank's Word Search II (LeetCode 212, hard) combines a trie of many words with a walk over a grid of letters. Try it after module 10 has taught grids and module 11's Word Search has taught how to mark a cell on the way in and put it back on the way out.
Last, say it the way you would in the room.
The interviewer asks you to build a trie with insert, search and starts_with, then asks why you would not use a set of words. Write what you would say: the brute force first, then the walk, the notebook, the promise and the cost of the trie.
Saved in this browser as you type.