Six interview problems about orders and cycles. The move: write every fact as a rule, then read the answer from the ready set at each step, or from a walk with three states.
You work on a build system, a payments platform, a photo album and a search index. The six problems on this street all give you facts of the form "this comes before that". You turn each fact into a rule and take nodes one at a time. The Academy calls this a topological sort.
The problems differ in which nodes take part, which ready node goes first, and what you read at the end.
| Problem | Nodes that take part | Which ready node goes first | What you read |
|---|---|---|---|
| Reentrant calls | every service, walked depth first | none: a walk with three states | the calls back to an open service |
| Feature flags with any-of rows | every flag | any ready flag | the flags that can be switched on |
| Rebuild only what changed | the changed targets and all that depend on them | the smallest id | the order |
| Settlement steps, report first | every step | the target's ancestors, then the smallest number | the order, or nothing on a cycle |
| How open is the album order | every photo | the smallest number | the places with a choice |
| Letters with a certain place | every letter that appears | none: you compare letters | the letters with a fixed place |
Read the third column. A queue gives one order. A heap with a key gives the order the problem asks for.
Exercise · Predict the output: In which order are the nodes taken?. Six nodes are numbered 0 to 5. Each pair is a rule: the first node comes before the second. The code takes the smallest ready node each time. What does it print?
n = 6
deps = [[2, 0], [4, 0], [2, 3], [2, 5], [4, 3]]
after = [[] for _ in range(n)]
waiting = [0] * n
for a, b in deps:
after[a].append(b)
waiting[b] += 1
ready = [v for v in range(n) if waiting[v] == 0]
order = []
while ready:
ready.sort()
a = ready.pop(0)
order.append(a)
for b in after[a]:
waiting[b] -= 1
if waiting[b] == 0:
ready.append(b)
print(*order)Count what each node waits for. Put the nodes that wait for nothing into the ready set. Take one, write it down, and lower the count of every node that waited for it. A node whose count reaches zero joins the ready set.
Three things are decided by that set.
A node is ready when everything before it is placed. Taking ready nodes one at a time lists every node of a graph without a cycle. The set's tie-break fixes the order, and its size counts the choices.
The Academy lesson Topological sort shows both methods. Here only one matters: count waiting, keep a ready set, and decide how it is ordered.
Take the smallest ready node, lower the counts of the nodes that waited for it, and let new nodes join the ready set.
Exercise · Put it in order: Take the smallest ready node. Arrange the lines into a function that takes the smallest ready node each time and returns the order. The lists after and waiting are already built from the rules.
def ready_order(after, waiting):
ready = [v for v in range(len(waiting)) if waiting[v] == 0]
order = []
while ready:
ready.sort()
a = ready.pop(0)
order.append(a)
for b in after[a]:
waiting[b] -= 1
if waiting[b] == 0:
ready.append(b)
return order
a = ready.pop()Exercise · Find the bug: Waiting for work that never happens. This returns the targets to rebuild: the changed ones and everything that depends on them, each after the targets it needs. For some inputs it leaves out targets that must be rebuilt. Which line is wrong?
def rebuild_order(n, deps, changed):
builds = [[] for _ in range(n)]
for a, b in deps:
builds[a].append(b)
affected = [False] * n
stack = list(changed)
while stack:
a = stack.pop()
if not affected[a]:
affected[a] = True
stack.extend(builds[a])
waiting = [0] * n
for a, b in deps:
waiting[b] += 1
ready = [t for t in range(n) if affected[t] and waiting[t] == 0]
order = []
while ready:
ready.sort()
a = ready.pop(0)
order.append(a)
for b in builds[a]:
waiting[b] -= 1
if waiting[b] == 0:
ready.append(b)
return orderThe Academy lesson Topological sort orders a whole graph and detects a cycle. Cycles, colouring and components shows the counting method for in-degrees. This street changes six things.
Only part of the graph takes part. The rebuild problem orders the changed targets and everything downstream of them. A target waits only for affected targets, as the bug above showed.
Take 8 targets with the rules 0 to 2, 1 to 2, 2 to 4, 3 to 4, 4 to 6, 5 to 6 and 6 to 7. Changing target 2 rebuilds only 2, 4, 6 and 7.
A key replaces the queue. Some ready nodes must go first. In the settlement problem, the steps the report needs come before every other step.
Take 7 steps with the rules 3 to 1, 1 to 5, 4 to 5, 0 to 6 and 2 to 6, and the report at step 5. The critical-first order is 3, 1, 4, 5, 0, 2, 6. The plain smallest-first order is 0, 2, 3, 1, 4, 5, 6 and reaches the report sixth, not fourth.
The size is the answer. The album problem counts the places where more than one photo is ready.
For the logs 0 1, 1 2 and 0 2 the count is 0, so the order is unique. For the logs 0 2 and 1 2 it is 1. When photos are left over, the logs contradict each other and the answer is -1.
The rules come from data. For the letter problem, compare each pair of neighbouring words. The first letters that differ give a rule, and a longer word before its own prefix means no order exists.
A letter has a certain place when the rules, with their chains, compare it with every other letter. For ab and cb there are 3 valid orders and no letter has a certain place. For ba, bc, ac and cab there is exactly one order, bac.
Exercise · Break it: Nodes left over. This counts the places where more than one photo is ready, as the logs allow. It must return -1 when the logs contradict each other. Find an input where it gives the wrong answer.
def count_open_choices(n, logs):
after = [[] for _ in range(n)]
waiting = [0] * n
for log in logs:
for i in range(len(log) - 1):
after[log[i]].append(log[i + 1])
waiting[log[i + 1]] += 1
ready = [p for p in range(n) if waiting[p] == 0]
open_choices = 0
while ready:
if len(ready) > 1:
open_choices += 1
ready.sort()
p = ready.pop(0)
for q in after[p]:
waiting[q] -= 1
if waiting[q] == 0:
ready.append(q)
return open_choicesThree states find a cycle. Take the calls 0 to 1, 1 to 2, 2 to 0, 2 to 2, and 1 to 2 again. Two calls, 2 to 0 and the self-call 2 to 2, return to an open service. The repeat of 1 to 2 reaches a finished one.
A row is met by any option. Take flags 0 to 3 with the rows 0 needs 1, 0 needs 3, 1 needs 2, and 2 needs any of 1 or 3. All 4 flags switch on, because flag 3 has no row. If flag 2 could use only flag 1, only 1 flag would work.
When the ready set empties, compare the number of placed nodes with n. Nodes left over wait on each other, so the answer is -1.
Solve them in this order. The first two find cycles and any-of rows. Then one limits the graph, one adds a key, one reads the size of the ready set, and the last builds the rules from data.
Before you code each problem, write the rules as pairs, say which nodes take part, and say how the ready set is ordered. Then say what you read at the end: the order, a count or a set of letters.
Give each problem about 25 minutes. Draw a graph of six nodes with two ready nodes at the start and write the ready set after every step.
Then write three small tests: no rules at all, a rule that repeats and a cycle of two nodes. A solution that handles all three has the counting and the leftover check right.
When an order is wrong, print the ready set at each step. Most wrong answers here come from counting nodes that do not take part, or from a tie-break the problem does not name.
Checkpoint · Topological order
Q1/5 When the ready set becomes empty but some nodes have not been placed, what does it mean?
Answer: B
The nodes left over each wait for another node that is also left over, so none of them can ever be ready.
Q2/5 Only some targets are rebuilt. A target needs targets 0 and 1, and only target 1 is being rebuilt. How many things does it wait for?
Answer: B
Target 0 will not be built in this run, so it can never free the target. Count a dependency only when its first target is affected.
Q3/5 Some ready steps must always go before others. Which structure holds the ready set?
Answer: C
A heap lets the best ready step leave first, even when new steps join the set. On the seven-step example the critical-first order puts the report fourth, and the plain smallest-first order puts it sixth.
Q4/5 When is the order of a set of rules unique?
Answer: C
If two nodes are ever ready together, either can go first. The album problem counts those steps as the open choices.
Q5/5 Two neighbouring words are abc and ab, in that order. What does the letter problem answer?
Answer: C
The words share the whole shorter word, so no letter decides the order, and the longer word comes first. No order of letters can sort that.
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.