Example 1
- Input
- numCourses = 2, prerequisites = [[1,0]]
- Output
- true
Take course 0 first, then course 1, so every course finishes.
Given a course count and prerequisite pairs, decide whether every course can be finished. The answer is yes exactly when the prerequisite graph has no directed cycle.
There are numCourses courses labeled 0 to numCourses - 1, plus an array prerequisites where prerequisites[i] = [a, b] means course b must be taken before course a.
Return true if all courses can be finished and false otherwise; a dependency cycle makes finishing impossible.
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= a, b < numCoursesTake course 0 first, then course 1, so every course finishes.
Course 1 needs course 0 while course 0 needs course 1, a cycle nobody can start.
The single course has no prerequisite, so it can be taken immediately. An empty edge list does not mean there are no courses.
Courses 2 then 3 can finish, but 0 and 1 require each other. Finishing one disconnected component is insufficient: every course must finish.
Finish 0, then 1 and 2 in either order, then 3. Course 3 becomes ready only after both of its prerequisites finish; a shared dependent is not a cycle.
A prerequisite pair [1,0] is a directed edge from 0 to 1: course 0 unlocks course 1. Count how many prerequisites of each course are still unfinished. A zero count means the course is ready; finishing it removes one requirement from each dependent. Example 1 starts with counts [0,1], then taking 0 changes them to [0,0] so 1 can finish too. A cycle has no first course, so if ready courses run out with any course unfinished, the answer is false.
Reveal Repeated Scan Kahn: intuition, complexity, and code
[a, b] as a directed edge from b to a, since b must come first.numCourses, the unplaced remainder holds the cycle, so answer false.true.[0, 0] is a one-course cycle and must return false.Cycle questions on directed graphs reduce to topological sorting: Kahn drains prerequisite-free nodes first, and anything left over proves a cycle.