Course Schedule

Medium

Topics
GraphTopological SortDFSBFS

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

01
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

01
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

  1. Build an adjacency list and in-degree count (edge b -> a).
  2. Queue all zero in-degree courses; repeatedly remove one and decrement its neighbours.
  3. 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 == n check 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==n
SensAI
Beta
Tap the mic to stop voice mode