Three interview problems that use every link once or find the link that holds a network together. The move: act when a depth-first walk finishes a node.
You work on a music app, a messaging service and a monitoring system. The three problems on this street walk a graph depth first. They do not use the walk to find out who is reachable. They use it to learn something at the moment a node finishes.
What a finished node tells you is different in each problem.
| Problem | The walk uses | A finished node tells you | The answer is |
|---|---|---|---|
| Replay a listening session | every handoff once, from a known start | it has no handoff left: write it down | the written nodes, reversed |
| Chain the relay hops | every hop once, with no start given | the same, and the start has one extra exit | the hops of the reversed path |
| Links whose loss splits the cluster | every link, depth first | the earliest visit time its subtree can reach | the links its subtree cannot go round |
The Academy lesson Topological sort already writes a node when it finishes, and reverses the list. This street uses the same idea on links.
Exercise · Predict the output: What is the session?. Three handoffs are listed: 0 to 1, 0 to 2 and 2 to 0. The session starts at track 0 and uses every handoff once. The code takes the smallest next track first, writes a track when it has no handoff left, and reverses the written tracks. What does it print?
edges = [[0, 1], [0, 2], [2, 0]]
out = [[] for _ in range(3)]
for a, b in sorted(edges, reverse=True):
out[a].append(b)
stack = [0]
path = []
while stack:
v = stack[-1]
if out[v]:
stack.append(out[v].pop())
else:
path.append(stack.pop())
path.reverse()
print(*path)A depth-first walk finishes a node only after every link below it has been used. So when a node finishes, everything about its part of the graph is known.
You decide what to record at that moment.
For a walk that uses every link once, record the node itself. A node with no unused link is a dead end for now, and dead ends are written first. The detours that lead back to the main walk are written after them. Reversed, the written nodes read as one walk that uses every link once.
For fragile links, record how far back the subtree can reach. Give each node a visit time. When a child finishes, the earliest time its subtree reaches tells you whether the link to the child is the only way across.
A depth-first walk finishes a node only after every link below it is used. So a finished node knows its dead ends, which are written first, and the earliest visit time its subtree can reach.
Write a node when it has no unused link left, then reverse the written nodes: dead ends come first, so they end up last.
Exercise · Find the bug: The path comes out backwards. This rebuilds the session from a list of handoffs. A session that uses every handoff once always exists. It prints a list of tracks in the wrong order. Which line is wrong?
def rebuild_session(handoffs, start):
out = {}
for a, b in sorted(handoffs, reverse=True):
out.setdefault(a, []).append(b)
stack = [start]
path = []
while stack:
v = stack[-1]
if out.get(v):
stack.append(out[v].pop())
else:
path.append(stack.pop())
return pathThe Academy lesson Topological sort shows the finish-and-reverse trick on nodes. BFS and DFS on any graph gives the depth-first walk, and Cycles, colouring and components shows why a repeated link matters. This street changes three things.
The walk uses links, not nodes. A node may be visited many times, because a session can return to the same track. Each link is taken once, so you remove it from a sorted list as you take it. Repeated links and links from a node to itself are allowed.
A greedy walk that always takes the smallest next link can get stuck. Take the handoffs 0 to 1, 0 to 2 and 2 to 0 from track 0. Greedy goes 0, 1 and stops with two handoffs unused. The finish-and-reverse walk gives 0, 2, 0, 1.
Check feasibility from the balance. Count exits minus entries for each node. A session needs every node to balance, or one node with one extra exit, the start, and one with one extra entry.
For the hops 5 to 6, 6 to 5 and 5 to 7, shard 5 has one extra exit, so it starts: 5, 6, 5, 7. The hops 0 to 1 and 2 to 3 have two separate starts, so no relay exists.
Trying every order of 9 handoffs checks 362,880 orders and finds 6 valid ones. The walk takes 19 stack steps.
Fragile links need the link number. A fragile link is one whose loss splits a group of services. When the walk comes back to the parent, skip the link it came by, not every link to the parent. Two links between the same services are a second route, so neither is fragile.
With 2 services and two links between them, skipping by the parent reports 1 fragile link. Skipping by the link number reports none, which is right. On 1,000 services and 1,500 links, removing each link in turn and counting groups costs 2,248,500 link checks. The walk looks at 3,000 links, and both find the same fragile link.
Exercise · Break it: The smallest next handoff. This rebuilds a session that uses every handoff once, from a known start. It always takes the smallest next handoff. When no session exists it must return an empty list. Find an input where it gives the wrong answer.
def rebuild_session(handoffs, start):
out = {}
for a, b in sorted(handoffs, reverse=True):
out.setdefault(a, []).append(b)
path = [start]
while out.get(path[-1]):
path.append(out[path[-1]].pop())
return pathA greedy walk that takes the smallest next handoff stops at the first dead end, even when handoffs are unused. Finish and reverse instead.
Solve them in this order. The first uses every link once from a known start, and the second also finds the start. The third learns from finished nodes how far back a subtree can reach.
Before you code each problem, write what a finished node tells you, and what you do with it. For the first two, also write how you know that a walk through every link exists.
Give each problem about 30 minutes. Draw a graph of five nodes with a loop through the start and a dead end hanging off it, and write the order in which nodes finish.
Then write three small tests: two separate pairs of links, a link from a node to itself and a repeated link. These break a walk that marks nodes as used, or one that skips the parent by node.
When an answer is wrong, print the order in which nodes finish. A session printed backwards is a missing reverse. A repeated link reported as fragile is a parent skipped by node.
Checkpoint · Itineraries and paths
Q1/5 In a walk that uses every link once, when is a node written down?
Answer: B
A node with no unused link is a dead end for now. Dead ends are written first, and the detours that lead back are written after them.
Q2/5 The nodes are written in the order they finish, and the list is 1, 0, 2, 0. What is the session?
Answer: B
The last track of the session finishes first, so the written list is the session backwards. Reverse it.
Q3/5 The hops are 5 to 6, 6 to 5 and 5 to 7. Where does the relay start?
Answer: C
Shard 5 has two exits and one entry. Shard 7 has one extra entry, and it is the end. The relay is 5, 6, 5, 7.
Q4/5 The handoffs are 0 to 1, 0 to 2 and 2 to 0, and the session starts at 0. What does a greedy walk that always takes the smallest next handoff return?
Answer: B
The greedy walk stops at track 1, which has no handoff. The finish-and-reverse walk finds 0, 2, 0, 1.
Q5/5 Two services share two links. A walk skips the link back to its parent by the parent node, not by the link number. What is the result?
Answer: B
By node, the walk skips both links to the parent, so the second link never counts as a route back. By link number it counts, and the pair is not fragile.
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.