Three interview problems where a walk builds something. The move: decide what the map from node to result stores, and fill it before you walk on.
You work on a search crawler, a chat app and a payments app. The three problems on this street walk a graph, as the Academy lessons do. This time the walk has a job: it records something about every node it reaches.
What it records is different each time.
| Problem | The walk may enter a node when | The map from node to result stores |
|---|---|---|
| Can the crawler reach the page | the page's level is within the clearance | seen, yes or no |
| Duplicate a workspace | the channel is not shared and not yet copied | the number of the channel's copy |
| Evaluate division queries | the kind has not been reached in its group | its value as a fraction of the first kind |
The map in the last column does two jobs. It records the result, and it tells the walk that a node has been reached already. That is why a graph with cycles, or a channel that links to itself, cannot make the walk run forever.
Exercise · Predict the output: Which copy gets which number?. A workspace has 4 channels, and channel 0 is copied first as number 4. The walk uses an explicit stack. It gives a channel the next number when it first sees the channel in a link list, and pushes it. What does it print?
links = [[1, 2], [3], [3], []]
new_id = [-1] * 4
new_id[0] = 4
next_id = 5
stack = [0]
while stack:
a = stack.pop()
for b in links[a]:
if new_id[b] == -1:
new_id[b] = next_id
next_id += 1
stack.append(b)
print(*new_id)Before you write the walk, decide what the map stores. It is a seen flag, the id of a copy, or a value. Then follow one rule.
Fill a node's entry when you first reach it, before you walk its links. A link that leads back to a node with an entry reuses that entry and goes no further. Cycles, repeated links and self-links all end in the same way.
A node's entry is written when the node is first reached, before its links are walked. A link back to a node with an entry reuses it, so each node is walked once and every cycle ends.
A second rule is about filters. When the walk may not enter some nodes, test the node you step onto, not the node you stand on. A node that is skipped is not walked through either, even when it links on to others.
Take four channels where channel 1 is shared and links to channel 3. From channel 0 the walk copies channels 0 and 2, and never reaches channel 3. A walk that went through the shared channel would copy channel 3 as well, and that is wrong.
Write a node's entry when you first reach it, before walking its links: a link back finds the entry and stops.
Exercise · Find the bug: The filter on the wrong page. A crawler may only visit pages with a level of at most its clearance. This returns true when it can reach the target. It checks the clearance with a test, but one line tests the wrong page. Which line is wrong?
def can_reach(n, links, levels, source, target, clearance):
out = [[] for _ in range(n)]
for a, b in links:
out[a].append(b)
if levels[source] > clearance:
return False
seen = [False] * n
seen[source] = True
stack = [source]
while stack:
a = stack.pop()
if a == target:
return True
for b in out[a]:
if levels[a] <= clearance and not seen[b]:
seen[b] = True
stack.append(b)
return FalseThe Academy lesson BFS and DFS on any graph already walks adjacency lists and clones a graph, and Graphs shows how to store them. This street does not repeat that. It adds three twists.
Skipped nodes and walk order. The workspace problem never copies a shared channel, and it never walks through one. The copies are numbered in the order a depth-first walk creates them.
Take the links [[1, 2], [3], [3], []]. A walk that numbers a channel when it first appears in a link list gives channels 0 to 3 the numbers 4, 5, 6, 7. A recursive depth-first walk gives 4, 5, 7, 6. Both are reasonable, and only one matches the problem.
A value instead of a flag. In the division problem each link carries a rate, and the reverse link carries its inverse. A walk from one kind to another multiplies the rates along the way.
Floats are not exact enough: 1 / 49 times 49 is 0.9999999999999999 in floating point.
Keep the value as two integers, a numerator and a denominator. After every step, divide both by their greatest common divisor.
One walk for many questions. Walking from the first kind of a group gives every other kind in the group a value relative to it. A query then divides two stored values.
Take 2,000 kinds in a chain and 1,000 random queries. A walk for each query makes 1,005,820 visits. One walk for the group makes 2,000 visits and then 1,000 lookups.
Exercise · Break it: The channel you must not walk through. This counts the copies a workspace duplication makes. A shared channel is never copied, and the walk must never go through it. Find an input where this gives the wrong count.
def copy_count(n, links, shared, start):
if shared[start] == 1:
return 0
seen = [False] * n
seen[start] = True
stack = [start]
copies = 1
while stack:
a = stack.pop()
for b in links[a]:
if not seen[b]:
seen[b] = True
stack.append(b)
if shared[b] == 0:
copies += 1
return copiesA shared channel is never copied, and the walk never goes through it. Marking it and pushing it lets the walk copy what lies behind it.
Solve them in this order. The first stores a flag, the second a copy and the third a value.
Before you code each problem, write what the map stores, what filter the walk applies, and what the walk order must be. For the division problem, also write what the value of the first node is.
Give each problem about 25 minutes. Draw a graph of five nodes with one cycle and one self-link before you code.
Then write three small tests: a start that is skipped, a node that links to itself, and two nodes that are never joined. Run each one by hand against the map before you run the code.
When an answer is wrong, print the map after the walk. A missing entry means the walk never reached the node. A wrong entry usually means the filter was on the wrong node or the walk order was different.
Checkpoint · Clone and copy
Q1/5 In a walk that builds a copy of a graph, when should a node's entry in the map be written?
Answer: B
A link that leads back to a node with an entry reuses the entry. That is what stops a cycle or a self-link from running forever.
Q2/5 The crawler may only visit pages at or below its clearance. At which page does the filter test belong?
Answer: B
The page it stands on was already allowed. The test must refuse a page before the crawler steps onto it.
Q3/5 Channel 1 is shared and links on to channel 3. The walk starts at channel 0, which links to 1. What happens to channel 3?
Answer: B
The shared channel is a wall for the walk. The channels behind it are reached only if another route leads to them.
Q4/5 Why keep a rate as two integers instead of a float?
Answer: C
Two integers in lowest terms stay exact after any number of multiplications, as long as they fit in the integer type.
Q5/5 There are 1,000 queries on 2,000 kinds that form one group. What is the cheapest way to answer them?
Answer: B
One walk for each query makes about a million visits. One walk for the group makes 2,000 visits, and each query is then a lookup.
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.