← Whiteboard questions

Course Schedule II

Find a build order that respects every dependency, smallest first

DSA, Medium, Graphs

Which structure or algorithm, and what does it cost.

A build has n modules, numbered 0 to n - 1. Each pair [a, b] in pairs means module a must be built before module b. Careful: here the first module of a pair is built first. Write build_order(n, pairs). It returns a list of all n modules in an order that obeys every pair. If several orders work, return the smallest one when compared from the front (the lexicographically smallest order): at each step, build the smallest-numbered module that is ready. If no order works, return an empty list.

Examples

Input n = 5, pairs = [[4,1],[4,3],[2,0],[0,3]]
Output [2, 0, 4, 1, 3]
Why modules 2 and 4 are ready at the start, and 2 goes first because it is smaller. Then 0 becomes ready and beats 4. Modules 1 and 3 become ready together, so 1 goes first.
Input n = 3, pairs = [[0,1],[1,2],[2,0]]
Output []
Why each module waits for the one before it in a circle, so none can start.
Input n = 1, pairs = []
Output [0]
Why one module and no pairs.

Constraints

Your answer must contain

Target Aim for O((n + p) log n) time and O(n + p) memory, where p is the number of pairs.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Draw an arrow from each module to the modules that need it. An order exists only if the arrows form no circle. Which module can you build first?

Hint 2 the approach

A module with no unbuilt prerequisite is ready. Build one, and the modules waiting on it may become ready. Which ready module should you pick when there are several?

Hint 3 the key step

Count each module's unbuilt prerequisites. Keep the ready ones in a min-heap, take the smallest, lower its followers' counts, and push any that reach zero.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every order of the n modules, from the smallest in dictionary order, and return the first one that obeys every pair. That is up to n! orders, and each check reads all pairs, so this only works for tiny n.

Best method

Count, for each module, how many pairs it still waits on, and list which modules each module unlocks. Keep every module with a count of 0 in a min-heap. Repeat: take the smallest module from the heap, add it to the order, and lower the count of each module it unlocks. A module that reaches 0 goes into the heap. Taking the smallest ready module each time gives the smallest order, because any smaller module that is not ready cannot go yet. A module inside a circle never reaches 0. At the end, return the order if it holds all n modules, and an empty list otherwise.

Hand trace

Example 1: the counts are [1, 1, 0, 2, 0], so the heap holds 2 and 4. Take 2: module 0 drops to 0, so the heap holds 0 and 4. Take 0: module 3 drops to 1. Take 4: modules 1 and 3 drop to 0, so the heap holds 1 and 3. Take 1, then 3. The order has 5 modules, so the answer is [2, 0, 4, 1, 3].

Code

import heapq
def build_order(n, pairs):
    after = [[] for _ in range(n)]      # after[a] = modules that need a first
    waiting = [0] * n                   # unbuilt prerequisites of each module
    for a, b in pairs:
        after[a].append(b)
        waiting[b] += 1
    ready = [i for i in range(n) if waiting[i] == 0]
    heapq.heapify(ready)
    order = []
    while ready:
        m = heapq.heappop(ready)        # the smallest ready module
        order.append(m)
        for nxt in after[m]:
            waiting[nxt] -= 1
            if waiting[nxt] == 0:
                heapq.heappush(ready, nxt)
    return order if len(order) == n else []

Time and memory

O((n + p) log n) time and O(n + p) memory, where p is the number of pairs. Each pair is read once, and each module enters and leaves the heap once at O(log n) each.

Common mistakes

  • Reading a pair backwards. In [a, b] module a must come first, so the arrow goes from a to b.
  • Using a plain queue when the statement asks for the smallest order. A queue builds modules in the order they became ready, which can give a larger order.
  • Returning a short list when there is a circle. If fewer than n modules were built, return an empty list.

Related problems

More Graphs problems
Course Schedule II: hints, walkthrough and Python solution