Course Schedule II

Medium

Topics
GraphTopological SortBFSDFS

There are n courses labelled 0 to n - 1. You are given edges where edges[i] = [a, b] means you must take course a before course b.

Return the length of a valid ordering in which all courses can be finished, or 0 if no such ordering exists.

The original problem returns the ordering itself. Because many orderings are valid, this judge asks for the length of the order you build — which is n exactly when a full topological sort succeeds, and 0 when a cycle blocks it. Build the real array, then return its length.

Example 1

0123
first course
Arrows point prerequisite → course. Several valid orders usually exist; any one is accepted.
A pair [a, b] means b must be taken before a; the arrow is drawn b → a.
Input:  n = 4, edges = [[1,0],[2,0],[3,1],[3,2]]
Output: 4
Explanation: One valid order is [3,1,2,0], so the length is 4.

Example 2

01
Only 0 of 2 courses can ever be unlocked, so a cycle exists and the answer is the empty list.
Input:  n = 2, edges = [[0,1],[1,0]]
Output: 0
Explanation: The two courses depend on each other, so no ordering exists.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • edges[i].length == 2
  • All pairs are distinct
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is Course Schedule with the order kept instead of thrown away. Kahn's algorithm gives it directly: repeatedly emit any course whose prerequisites are all satisfied. The emitted sequence is the answer, and its length tells you whether the sort completed — a short list means the leftover courses form a cycle.

Approach

  1. Build the adjacency list and in-degree array. Note the direction: an edge [a, b] contributes to indeg[b].
  2. Push every zero in-degree course into a queue; these have no unmet prerequisites.
  3. Pop a course, append it to the output order, and decrement each neighbour's in-degree. Push a neighbour the moment its in-degree hits zero.
  4. If the output holds all n courses, it is a valid ordering, so return n. Otherwise a cycle stalled the queue early and no ordering exists, so return 0.
from collections import deque

class Solution:
    def findOrderLength(self, n, edges):
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for a, b in edges:
            adj[a].append(b)
            indeg[b] += 1
        q = deque(i for i in range(n) if indeg[i] == 0)
        order = []
        while q:
            cur = q.popleft()
            order.append(cur)
            for nxt in adj[cur]:
                indeg[nxt] -= 1
                if indeg[nxt] == 0:
                    q.append(nxt)
        return len(order) if len(order) == n else 0

Dry Run

n = 4, prerequisites [1,0] [2,0] [3,1] [3,2], read as a -> b
  adj [[], [0], [0], [1, 2]]      indeg [2, 1, 1, 0]
  seed with every in-degree 0 node:  [3]
  take 3   indeg [2, 0, 0, 0]   appends 1 and 2   order [3, 1, 2]
  take 1   indeg [1, 0, 0, 0]   appends nothing   order [3, 1, 2]
  take 2   indeg [0, 0, 0, 0]   appends 0         order [3, 1, 2, 0]
  take 0   indeg [0, 0, 0, 0]   appends nothing   order [3, 1, 2, 0]
len(order) = 4 = n, so the ordering is complete
answer 4
The list IS the queue -- `i` is a read cursor walking forward over the same array
that is being appended to, which is why there is no separate deque. A node is
appended exactly when its in-degree reaches 0, so it is enqueued once and never
revisited.
Note that 1 appends nothing while 2 appends 0. Course 0 has two prerequisites, so
the first of them to be taken merely decrements it to 1; only the second releases
it. That is precisely why the decrement belongs on the POP and not on discovery --
decrement when a node is first seen and 0 would be enqueued twice.
The length comparison is the cycle check, and a fully cyclic graph hides how much
work it does, because the order comes out empty and 0 is returned either way.
A partly cyclic graph shows it: n = 3 with edges [0,1] and [1,0] leaves node 2
free, so the order is [2] with length 1 -- the shipped version returns 0, and
without the comparison it returns 1, a confident answer for an impossible
schedule.

Complexity

  • Time — O(V + E) — every course enters and leaves the queue at most once.
  • Space — O(V + E) for the graph, in-degrees, queue, and output.

Common Pitfalls

  • Reversing the edge direction produces a valid ordering of the mirrored problem, which is wrong here. Be deliberate about which endpoint gains in-degree.
  • Returning a partial order on a cyclic graph is the most common failure. Always compare the output length to n before returning.
  • Decrement in-degree when you pop a course, not when you discover it, or a node with two prerequisites can be enqueued twice.
  • A DFS post-order reversal works too, but needs a separate on-stack marker to detect cycles — a plain visited set is not enough.

Full Solution — all languages

class Solution:
    def findOrderLength(self, n, edges):
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for a, b in edges:
            adj[a].append(b)
            indeg[b] += 1
        order = [i for i in range(n) if indeg[i] == 0]
        i = 0
        while i < len(order):
            course = order[i]
            i += 1
            for after in adj[course]:
                indeg[after] -= 1
                if indeg[after] == 0:
                    order.append(after)
        return len(order) if len(order) == n else 0
SensAI
Beta
Tap the mic to stop voice mode