Four problems where a trie does more than store words. The move: choose what the key is and what each node stores, so that one walk down the trie answers the question.
You work on a shop search box, a build platform, a chat game and a release tool. The four problems on this street come from these, and each one keeps a trie. The trie is the same structure you know from the Academy, but the key and the node change from problem to problem.
The table shows the key that each problem inserts and what the walk does.
| Problem | The key | A node stores | The walk |
|---|---|---|---|
| Suggestion words with wildcard counts | the letters of a word | whether a word ends here | follows one child, or every child for a dot |
| The most different pair of build fingerprints | a number in 20 bits, highest first | nothing but its children | prefers the child with the opposite bit |
| Every dictionary word hidden in a letter grid | the letters of a word | the word that ends here | follows the grid, and stops at a missing child |
| Newest build label with a given start and end | suffix, a separator and the label | the newest position that passed here | spells the suffix, the separator and the prefix |
Read the second and third columns together. What the node stores decides what a query can return, and the key decides which questions turn into a prefix.
Here is the first problem on a small book of words. The code builds the trie, then follows the pattern c.t level by level. A dot continues into every child.
Exercise · Predict the output: Nodes and matches. The book holds the words cat, cot, cut, cart and ca. The code builds a trie, with node 0 as the root, and then follows the pattern c.t. What does it print: the number of nodes, and the number of words that match?
words = ["cat", "cot", "cut", "cart", "ca"]
kids = [{}]
ends = [False]
for w in words:
node = 0
for ch in w:
if ch not in kids[node]:
kids.append({})
ends.append(False)
kids[node][ch] = len(kids) - 1
node = kids[node][ch]
ends[node] = True
frontier = [0]
for ch in "c.t":
nxt = []
for node in frontier:
if ch == ".":
nxt.extend(kids[node].values())
elif ch in kids[node]:
nxt.append(kids[node][ch])
frontier = nxt
print(len(kids), sum(1 for node in frontier if ends[node]))The move has two parts, and you decide both before any code.
First, choose the key so that the question becomes a prefix. For suggestions the key is the word. For xor it is the number, written from its highest bit, because a 1 in a high place beats any bits below it. For prefix and suffix it joins both ends of a word into one string.
Second, choose what a node stores. An end flag answers "is this a word". A word stored at its end node answers "which word". A stamp of the newest position, written into every node on the path, answers "the newest label that passes here".
After a key is inserted, every node on its path can answer for all keys that share that prefix, so one walk to the node answers the question.
Then the walk does the rest. It may branch, as a dot does, or be steered, as the xor walk is, and it stops the moment a child is missing.
The cost is small. For 20,000 numbers of 20 bits the trie has at most 400,001 nodes, and the queries take 800,000 steps in all. Comparing every pair would take 400,000,000.
Read bits from the highest, and prefer the child with the opposite bit. Five against 2, 7 and 4 finds 5 xor 2 = 7.
The xor walk has one choice at each bit, and it is easy to choose the wrong child.
Exercise · Find the bug: The nearest number, not the farthest. This finds the largest xor of one old fingerprint and one new fingerprint. It builds a trie of the old numbers, then walks it for each new number. It returns a wrong answer. Which line is wrong?
def max_xor_across(old_builds, new_builds):
bits = 20
child = [[-1, -1] for _ in range(len(old_builds) * bits + 1)]
used = 1
best = 0
for x in old_builds:
node = 0
for bit in range(bits - 1, -1, -1):
b = (x >> bit) & 1
if child[node][b] == -1:
child[node][b] = used
used += 1
node = child[node][b]
for y in new_builds:
node = 0
found = 0
for bit in range(bits - 1, -1, -1):
want = (y >> bit) & 1
if child[node][want] == -1:
want ^= 1
node = child[node][want]
found |= want << bit
best = max(best, found ^ y)
return bestThe Academy lesson Tries stores words and answers prefix questions. String basics gave you comparison and counting on strings, and Bits and maths basics gave you shifts and masks. This street changes three things about the trie.
The key is built for the question. A number becomes 20 steps of one bit each. For the prefix and suffix problem, every suffix of a label is joined to the label by a separator. A query for a suffix and a prefix is then one string.
A label of 7 letters adds at most 105 nodes, and 5,000 labels add at most 525,001.
The node stores more than a flag. A stamp of the newest position, written into every node on the path, lets a query read the answer at the end of its walk. An erased word, as in the grid problem, is a node whose stored word is cleared: the node stays, and longer words below it stay too.
The walk is steered by something else. In the grid problem a depth-first walk over cells moves down the trie as it moves over the grid, and it stops where the trie has no child. On a grid of 64 letters from a to e and 1,706 different words, one walk from every cell takes 4,351 steps. Searching for each word on its own takes 213,182 steps, and both find the same 434 words.
A pattern that reaches a node on the path of a longer word does not match. Ask the end flag.
A dot makes the walk branch, and there is one more trap: a node that is reached is not always a word.
Exercise · Break it: A node that is only a prefix. This counts the words of a book that match a pattern, where a dot matches any one letter. It follows the pattern through a trie. Find an input where it gives the wrong count.
def count_matches(words, pattern):
kids = [{}]
for w in words:
node = 0
for ch in w:
if ch not in kids[node]:
kids.append({})
kids[node][ch] = len(kids) - 1
node = kids[node][ch]
frontier = [0]
for ch in pattern:
nxt = []
for node in frontier:
if ch == ".":
nxt.extend(kids[node].values())
elif ch in kids[node]:
nxt.append(kids[node][ch])
frontier = nxt
return len(frontier)Solve them in this order. The first uses a flag and a branching walk. The second changes the key to bits. The third lets another search steer the walk, and the fourth builds one string out of two ends.
Before you code each problem, write three lines: what the key is, what each node stores, and how the walk moves. Then count the nodes. A key of length L adds at most L nodes, and a word with all its suffixes adds at most L times 2L plus 1.
Give each problem about 30 minutes. Spend the first five on the three lines and the node count.
Check these before you submit.
Checkpoint · Tries and strings, in depth
Q1/5 For the largest xor of two numbers, in which order do you read the bits of each number, and which child does the walk prefer?
Answer: D
A 1 in a high place of the xor is worth more than all the bits below it, so the walk decides the high bits first. A bit of the xor is 1 when the two bits differ.
Q2/5 A book holds the word cart only. How many words match the pattern car, and why can a trie without end flags get this wrong?
Answer: B
A node that the walk reaches is only a word if the book ended a word there. Without the end flag, the count includes every prefix.
Q3/5 In the prefix and suffix problem, what is inserted into the trie for each suffix of each label?
Answer: C
A query walks suffix, separator, prefix. The separator keeps the suffix and the label apart, and the stamp at each node holds the newest label that passes there.
Q4/5 A label has 7 letters, and the trie holds every suffix joined to the label. About how many nodes can one label add?
Answer: C
Each key is at most 7 + 1 + 7 = 15 symbols long, and a label has 7 suffixes. That is at most 7 times 15, which is 105 nodes.
Q5/5 In the grid problem, why does one walk from every cell with a trie beat searching for each word on its own?
Answer: B
On the lesson's grid, one trie walk takes 4,351 steps and searching each of the 1,706 words alone takes 213,182. The walk stops when no word starts that way.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.