Four interview problems about the longest chain of dependencies. The move: take nodes in topological order and hand a value forward to each later node.
You work on a bank's month-end close, a video platform, a warehouse fit-out and a messaging platform. The four problems on this street give you dependencies, as the topological order street does. This time you want a number: how long the longest chain is.
The number is different each time.
| Problem | The value handed forward | The answer is |
|---|---|---|
| Fewest days to close every ledger | the day a ledger closes | the largest day |
| Most stages one worker pool handles | a count of stages for each pool | the largest count of one pool |
| Earliest day the fit-out is done | the day a task is done | the latest finish |
| Pipeline stages that run in pools | none: the order itself | an order where each pool is unbroken |
Read the second column. A chain of dependencies is a path, and the longest path in a graph without cycles is easy to find in one pass.
Exercise · Predict the output: On which day does each ledger close?. Six ledgers are numbered 0 to 5. Each pair is a feed: the first ledger must close on an earlier day than the second. Every ledger with no feeder closes on day 1. What does the code print?
n = 6
feeds = [[0, 2], [1, 2], [2, 3], [1, 4], [4, 3], [3, 5]]
after = [[] for _ in range(n)]
waiting = [0] * n
for a, b in feeds:
after[a].append(b)
waiting[b] += 1
day = [1] * n
queue = [v for v in range(n) if waiting[v] == 0]
for a in queue:
for b in after[a]:
day[b] = max(day[b], day[a] + 1)
waiting[b] -= 1
if waiting[b] == 0:
queue.append(b)
print(*day)Take nodes in topological order. When you take a node, you hand its value to every node that comes after it, and you keep the better value there. The value is a day, a count or a finish time, and "better" is almost always the larger one.
A node leaves the ready set only after every one of its predecessors has been taken. So by then every predecessor has handed its value forward, and the node's own value is final.
A node is taken after all its predecessors, and each of them has handed its value forward with max. So the node's value is final when it is taken, and the answer is the best value over all nodes.
Take care to hand the value forward with max. A node with two predecessors receives two values, and it must keep the larger. Writing the value with a plain assignment keeps whichever predecessor was taken last.
The size of the graph matters too. In a layered graph of 12 layers with 3 ledgers each, where every ledger feeds all 3 in the next layer, there are 531,441 paths. The one pass looks at the 99 feeds and finds the longest chain of 12 days.
Take nodes in topological order and hand each value forward with max: a node's value is final when it is taken.
Exercise · Find the bug: The slower task is forgotten. This returns the earliest day on which every task is done. A task can start only when all tasks it needs are done. It gives too small an answer on some inputs. Which line is wrong?
def earliest_finish(durations, needs):
n = len(durations)
waiting = [0] * n
unlocks = [[] for _ in range(n)]
for a, b in needs:
unlocks[a].append(b)
waiting[b] += 1
start = [0] * n
ready = [v for v in range(n) if waiting[v] == 0]
seen = 0
answer = 0
while ready:
a = ready.pop()
seen += 1
done = start[a] + durations[a]
answer = max(answer, done)
for b in unlocks[a]:
start[b] = done
waiting[b] -= 1
if waiting[b] == 0:
ready.append(b)
return answer if seen == n else -1The Academy lesson Topological sort lists the nodes in order and detects a cycle. Cycles, colouring and components gives the in-degree counts. This street changes three things.
The value is a vector. The pool problem asks for the most stages of one pool on any chain. Hand forward a count for each pool, 26 numbers per stage, keeping the larger count of each pool.
Take one chain of 7 stages with the pools a, b, a, b, a, b, a and another chain of 5 stages, all a. The longest chain has 7 stages, but the answer is 5, because the first chain holds only 4 of pool a.
The value has a weight. In the fit-out problem a task takes days. Its value is its start plus its duration.
Take 6 tasks with durations 3, 2, 4, 1, 2, 5. The needs are 0 to 2, 1 to 2, 2 to 4, 3 to 4 and 4 to 5. The earliest finish is day 14. The durations add up to 17, so the parallel crews save 3 days.
The groups are a second graph. In the pipeline problem, all stages of a pool must run in one unbroken session. Sort the pools as nodes of a graph, with a rule between two pools when a rule crosses them. Then sort the stages inside each pool.
A group order can fail when no stage order does. Say stage 0 in pool 0 comes before stage 1 in pool 1, and stage 3 in pool 1 comes before stage 2 in pool 0.
The stages have an order. The pools do not: each would have to run first.
Exercise · Break it: The ledger with no feeder. This returns the fewest days needed to close every ledger, or -1 when the feeds contain a loop. Find an input where it gives the wrong answer.
def fewest_close_days(n, feeds):
after = [[] for _ in range(n)]
waiting = [0] * n
for a, b in feeds:
after[a].append(b)
waiting[b] += 1
day = [1] * n
ready = [v for v in range(n) if waiting[v] == 0]
seen = 0
answer = 0
while ready:
a = ready.pop()
seen += 1
for b in after[a]:
day[b] = max(day[b], day[a] + 1)
answer = max(answer, day[b])
waiting[b] -= 1
if waiting[b] == 0:
ready.append(b)
return answer if seen == n else -1Update the answer when a node is taken. If you update it only on a feed, a ledger that no feed touches never counts.
Solve them in this order. The first hands forward a day, the second a vector, the third a weighted finish time, and the last sorts groups.
Before you code each problem, write the value you hand forward, how a node combines its predecessors, and what the answer reads. For the last problem, also write what the groups are as nodes.
Give each problem about 30 minutes. Draw a graph of six nodes with two chains of different lengths and write the value of every node by hand.
Then write three small tests: a graph with no dependencies, a single chain and a loop. A solution that handles all three has the starting values, the max and the loop check right.
When an answer is too small, check that you used max when handing the value forward. When it is zero for a graph without dependencies, check where you update the answer.
Checkpoint · Dependency resolution
Q1/5 Why is a node's value final at the moment the node is taken from the ready set?
Answer: B
A node joins the ready set only when everything it waits for has been taken, so all the values it will ever receive are already in.
Q2/5 A task needs two other tasks. How should it receive their finish times?
Answer: C
The task cannot start until its slowest prerequisite is done. An assignment keeps the last value written, which can be the smaller one.
Q3/5 One chain has 7 stages with the pools a, b, a, b, a, b, a. Another has 5 stages, all of pool a. What is the most stages of one pool on any chain?
Answer: C
The first chain holds only 4 stages of pool a, and the second holds 5. The longest chain, with 7 stages, is not the answer.
Q4/5 Six tasks have durations 3, 2, 4, 1, 2 and 5, which add up to 17. The earliest finish with parallel crews is 14. What does 14 measure?
Answer: B
Tasks off the longest chain run in parallel, so only the longest chain decides the finish. Here that saves 3 days.
Q5/5 Stage 0 in pool 0 must run before stage 1 in pool 1, and stage 3 in pool 1 must run before stage 2 in pool 0. Can each pool run in one unbroken session?
Answer: C
The stages alone have an order, but as nodes the pools form a cycle. An unbroken session for each pool is then impossible.
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.