You must take numCourses courses labelled 0 .. numCourses-1. Some have prerequisites: prerequisites[i] = [a, b] means you must take course b before course a. Return true if you can finish all courses, and false otherwise.
Input: numCourses = 2, prerequisites = [[1,0]] Output: true Take 0, then 1.
Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false 0 and 1 each require the other — a cycle.
- 1 <= numCourses <= 10^5 - 0 <= prerequisites.length <= 10^5 - no duplicate prerequisite pairs
Model prerequisites as a directed graph: [a, b] (take b before a) is an edge b → a. You can finish all courses iff this graph has no directed cycle — a cycle is a set of courses each waiting on another, impossible to start. So the whole problem is a directed-cycle test:
numCourses, it's a DAG (finishable); if some remain, they're stuck in a cycle.Both are O(V + E).
“Direction of the edge?”
[a, b] means b before a, so the edge points b -> a.
“When is it impossible?”
Exactly when the prerequisite graph has a cycle.
Prerequisites form a directed graph; I can finish everything iff it has no cycle.
I run Kahn's and check all courses get ordered, or DFS for a back edge.
Worked example — numCourses = 2, prerequisites = [[1,0],[0,1]]
edges 0->1 and 1->0 form a cycle -> no course has in-degree 0 -> cannot finish -> false
[a, b] ⇒ b → a.
A DAG always has a valid order.
Leftover courses indicate a cycle.
| Kahn's algorithm | DFS recursion stack | |
|---|---|---|
| Signal | ordered count == numCourses | no back edge |
| Time | O(V+E) | O(V+E) |
| Also gives | a valid order | the offending cycle |
Both answer the same finishability question. Full code is in the Approaches selector below.
Key takeaway
You can finish all courses iff the prerequisite graph (edge b → a) is acyclic. Kahn's (order all V) or DFS (no back edge). O(V+E).
build edges b -> a return "no directed cycle"