download

Can you take every course, and which ones stay blocked?

Algorithms~20 minReviewed 1 Nov 2026Free · No sign-in

Question

There are n courses, numbered 0 to n - 1. A pair (a, b) means you must finish course a before course b. Write plan(n, prereqs). Return two lists: an order in which you can take courses, and the sorted list of courses you can never take. Any valid order is fine.

"PYTHON"
plan(6, [(0, 3), (1, 3), (3, 4), (2, 5), (5, 2), (5, 4)])
# ([1, 0, 3], [2, 4, 5]); [0, 1, 3] is also a valid order
plan(6, [(0, 3), (1, 3), (3, 4), (2, 5), (5, 4)])
# all six courses in a valid order, and []
"CODE · PYTHON"
def plan(n, prereqs):
    ...
Show hints (3)
  1. "COUNT WHAT'S MISSING"

    For each course, count the prerequisites that are not done yet. Which courses can you start right now?

  2. "UNLOCK AS YOU GO"

    When you finish a course, lower the count of every course it unlocks. A course whose count drops to 0 is ready.

  3. "WHAT'S LEFT"

    Stop when no course is ready. Every course with a count above 0 is blocked. Ask yourself: is each of them really on a cycle?

Show checked explanation

Use Kahn's algorithm. Count the unfinished prerequisites of each course. Take any course whose count is 0, and lower the counts of the courses it unlocks. Repeat until nothing is ready. If every course was taken, that is the plan. Otherwise the courses left are blocked: they are on a cycle or depend on one.

"SOLUTION · PYTHON"
def plan(n, prereqs):
    needs = [0] * n
    unlocks = [[] for _ in range(n)]
    for before, after in prereqs:
        needs[after] += 1
        unlocks[before].append(after)
    ready = [c for c in range(n) if needs[c] == 0]
    order = []
    while ready:
        course = ready.pop()
        order.append(course)
        for nxt in unlocks[course]:
            needs[nxt] -= 1
            if needs[nxt] == 0:
                ready.append(nxt)
    return order, [c for c in range(n) if needs[c] > 0]


print(plan(6, [(0, 3), (1, 3), (3, 4), (2, 5), (5, 2), (5, 4)]))
print(plan(6, [(0, 3), (1, 3), (3, 4), (2, 5), (5, 4)]))
"OUTPUT"
([1, 0, 3], [2, 4, 5])
([2, 5, 1, 0, 3, 4], [])

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Take the first example. needs[c] counts the prerequisites of course c that are not done yet. At the start it is [0, 0, 1, 2, 2, 1], so courses 0 and 1 are ready. The ready courses sit in a plain list, and pop() takes the last one:

takeeffectneeds afterready after
1course 3 drops to 1[0, 0, 1, 1, 2, 1][0]
0course 3 drops to 0[0, 0, 1, 0, 2, 1][3]
3course 4 drops to 1[0, 0, 1, 0, 1, 1][]

Nothing is ready, so the order is [1, 0, 3]. Courses 2, 4 and 5 still need something, so they are blocked.

Why are they blocked? Courses 2 and 5 each need the other, so neither can start. Course 4 is on no cycle. Its prerequisite 3 is done, but it also needs 5, which waits on the cycle. So the blocked list holds every course on a cycle, plus every course that depends on one, directly or not.

The reverse also holds: if any course is left, there is a cycle. Each blocked course has an unfinished prerequisite, and that one is blocked too. Follow them backwards. There are only n courses, so you must come back to one you saw. That is a cycle.

Remove the pair (5, 2) and the cycle is gone. Now course 2 is ready at the start, and the second call returns all six courses and [].

Each course enters ready at most once. Each pair is handled once when counting and once when unlocking. That is O(n + e) time for e pairs, with no recursion.

Common mistakes

  • Calling every blocked course part of a cycle. In the example, course 4 is blocked but is on no cycle. It only waits for course 5.
  • Storing unlocks as sets while needs counts every pair. A repeated pair (1, 3) adds 2 to needs[3] but takes away only 1, so course 3 never becomes ready.
  • Returning order as the full plan without comparing len(order) with n. A shorter order means some courses can never be taken.
  • Using recursive DFS on a long chain. Python's default recursion limit is 1000 (sys.getrecursionlimit()), so a chain of 2,000 courses raises RecursionError. Kahn's algorithm is a plain loop.

Follow-up questions

  • "Is the order unique? What if the lowest-numbered ready course must go first?" It is not unique: [0, 1, 3] is as valid as [1, 0, 3]. For the lowest-numbered order, keep the ready courses in a min-heap with heapq.heappush and heapq.heappop. On the second example that gives [0, 1, 2, 3, 5, 4]. The total cost becomes O(n log n + e).
  • "Which blocked courses are really on a cycle?" Find the strongly connected components, for example with Tarjan's algorithm. A course is on a cycle if its component has two or more courses, or if it requires itself. In the example, {2, 5} is such a component, and course 4 is a component on its own.
  • "Is there something in the standard library?" Yes, graphlib.TopologicalSorter. Its static_order() yields a valid order, or raises graphlib.CycleError if there is a cycle. The error names one cycle, not every blocked course. For this task you still count prerequisites yourself.

What a strong answer covers

Explains needs in plain words. Knows that leftover courses prove a cycle, and that some of them only depend on one. Gives O(n + e), handles repeated pairs and knows the order is not unique.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Coding Interview Patterns (Alex Xu and Shaun Gunawardane, 2024); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.