Course Schedule
Medium
Topics
There are n courses labeled 0..n-1. edges[i] = [a, b] means you must take course b before course a. Return true if you can finish all courses.
Example 1
An arrow points from a prerequisite to the course that needs it. All 2 courses can be finished exactly when this graph has no cycle. Peeling off courses with no remaining prerequisites clears all 2, so the answer is
true.A pair
[a, b] means b must be taken before a; the arrow is drawn b → a.Input: n = 2, edges = [[1,0]] Output: true
Example 2
stuck in a cycle
The shaded nodes never reach in-degree 0, so they form a cycle and the answer is
false.Input: n = 2, edges = [[1,0],[0,1]] Output: false
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
Editorial — intuition, approach, complexity and pitfalls
Intuition
You can finish all courses exactly when the prerequisite graph has no cycle. Topological sort (Kahn’s algorithm) succeeds iff every node can be ordered, i.e. no cycle.
Approach
- Build an adjacency list and in-degree count (edge b -> a).
- Queue all zero in-degree courses; repeatedly remove one and decrement its neighbours.
- If the number removed equals n, there is no cycle.
Dry Run
n = 2, prerequisites [[1,0]] -- "1 needs 0", so the edge runs 0 -> 1
adj [[1], []] indeg [0, 1]
queue seeded with every in-degree 0 node: [0]
take 0 seen=1 indeg [0, 0] releases 1 queue [1]
take 1 seen=2 indeg [0, 0] releases nothing
seen 2 of 2 -> true
n = 2, prerequisites [[1,0],[0,1]] -- each needs the other
adj [[1], [0]] indeg [1, 1]
queue seeded with every in-degree 0 node: [] -- there are none
the while loop never executes at all
seen 0 of 2 -> false
The cyclic case is the one to look at, and it fails quietly. There is no error, no
detection step, no colour marking: the queue simply starts empty and Kahn's
algorithm has nothing to do. On a graph that is part cyclic and part not it would
drain the acyclic part and then stop early. Either way the cycle shows up as
"seen fell short of n", which is why that comparison IS the answer -- return true
unconditionally and every input, cycles included, reports as schedulable.
In-degree is the mechanism worth naming. A course becomes available the moment
its last outstanding prerequisite is removed, which is exactly indeg hitting 0,
so each node is enqueued once and each edge decrements once -- O(V + E) with no
revisiting.
Edge direction is a choice here, not a constraint. Reversing every edge preserves
whether a cycle exists, and this question only asks that. It would start to matter
the moment the ORDER had to be printed.Complexity
- Time — O(V+E): each node and edge processed once.
- Space — O(V+E): adjacency list and queue.
Common Pitfalls
- The
seen == ncheck is the entire answer. Kahn's algorithm drains the queue happily on a cyclic graph -- it just never reaches every node -- so returning true unconditionally reports every input as schedulable, cycles included. - Reversing the edge direction is not a bug for this question, and that is worth understanding rather than memorising: reversing a graph preserves whether it has a cycle, and "can all courses be finished" only asks that. It would matter the moment you had to output the order.
Full Solution — all languages
class Solution:
def canFinish(self, n, edges):
adj=[[] for _ in range(n)]
indeg=[0]*n
for a,b in edges:
adj[b].append(a); indeg[a]+=1
from collections import deque
q=deque(i for i in range(n) if indeg[i]==0)
seen=0
while q:
u=q.popleft(); seen+=1
for v in adj[u]:
indeg[v]-=1
if indeg[v]==0: q.append(v)
return seen==nimport java.util.*;
class Solution {
public boolean canFinish(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[1]).add(e[0]);
indeg[e[0]]++;
}
Deque<Integer> q=new ArrayDeque<>();
for(int i=0;i<n;i++)if(indeg[i]==0)q.add(i);
int seen=0;
while(!q.isEmpty()) {
int u=q.poll();
seen++;
for(int v:adj.get(u))if(--indeg[v]==0)q.add(v);
}
return seen==n;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool canFinish(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
vector<int> indeg(n,0);
for(auto& e:edges) {
adj[e[1]].push_back(e[0]);
indeg[e[0]]++;
}
queue<int> q;
for(int i=0;i<n;i++)if(indeg[i]==0)q.push(i);
int seen=0;
while(!q.empty()) {
int u=q.front();
q.pop();
seen++;
for(int v:adj[u])if(--indeg[v]==0)q.push(v);
}
return seen==n;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/ var canFinish = function(n, edges) {
const adj=Array.from({length:n},()=>[]),indeg=new Array(n).fill(0);
for(const e of edges) {
adj[e[1]].push(e[0]);
indeg[e[0]]++;
}
const q=[];
for(let i=0;i<n;i++)if(indeg[i]===0)q.push(i);
let seen=0;
while(q.length) {
const u=q.shift();
seen++;
for(const v of adj[u]) {
if(--indeg[v]===0)q.push(v);
}
}
return seen===n;
};