Course Schedule II
Medium
Topics
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
[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
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
- Build the adjacency list and in-degree array. Note the direction: an edge
[a, b]contributes toindeg[b]. - Push every zero in-degree course into a queue; these have no unmet prerequisites.
- 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.
- If the output holds all
ncourses, it is a valid ordering, so returnn. 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 0Dry 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
nbefore 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 0import java.util.*;
class Solution {
public int findOrderLength(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
indeg[e[1]]++;
}
List<Integer> order = new ArrayList<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) order.add(i);
for (int i = 0; i < order.size(); i++) {
for (int after : adj.get(order.get(i))) {
if (--indeg[after] == 0) order.add(after);
}
}
return order.size() == n ? n : 0;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findOrderLength(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
vector<int> indeg(n, 0);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
indeg[e[1]]++;
}
vector<int> order;
for (int i = 0; i < n; i++) if (indeg[i] == 0) order.push_back(i);
for (size_t i = 0; i < order.size(); i++) {
for (int after : adj[order[i]]) {
if (--indeg[after] == 0) order.push_back(after);
}
}
return (int)order.size() == n ? n : 0;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/ var findOrderLength = function(n, edges) {
const adj = Array.from({ length: n }, () => []);
const indeg = new Array(n).fill(0);
for (const e of edges) {
adj[e[0]].push(e[1]);
indeg[e[1]]++;
}
const order = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) order.push(i);
for (let i = 0; i < order.length; i++) {
for (const after of adj[order[i]]) {
if (--indeg[after] === 0) order.push(after);
}
}
return order.length === n ? order.length : 0;
};