Course Schedule

medium · graph, topological-sort, cycle-detection

Course Schedule

You are given numCourses labeled from 0 to numCourses-1 and a list of prerequisite pairs. Each pair [a, b] means you must take course b before course a.

Return true if you can finish all courses, otherwise return false.

Function signature

func CanFinish(numCourses int, prerequisites [][]int) bool

Examples

Example 1:

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: Take course 0, then course 1.

Example 2:

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There is a cycle (0 -> 1 -> 0).

Example 3:

Input: numCourses = 4, prerequisites = [[1,0],[2,1],[3,2]]
Output: true

Constraints

  • 1 <= numCourses <= 10^5
  • 0 <= prerequisites.length <= 2*10^5
  • 0 <= a, b < numCourses

Hints

  1. This is a cycle detection problem in a directed graph.
  2. Use topological sorting (Kahn's algorithm) or DFS with colors.
  3. If you can visit all nodes without hitting a cycle, you can finish.

Notes

  • Courses with no prerequisites can be taken in any order.
  • If there is a cycle, no valid ordering exists.
Run tests to see results
No issues detected