There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1.

You are given an array prerequisites where prerequisites[i] = [a_i, b_i] indicates that you must take course b_i first if you want to take course a_i.

For example, the pair [0, 1] indicates that to take course 0 you have to first take course 1.

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

Input & Output

Example 1 — Basic Valid Case
$ Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
💡 Note: Course 1 requires course 0 first. Valid order: take course 0, then course 1. No circular dependency.
Example 2 — Circular Dependency
$ Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
💡 Note: Course 1 requires course 0, but course 0 requires course 1. This creates a cycle, making it impossible to complete all courses.
Example 3 — No Prerequisites
$ Input: numCourses = 3, prerequisites = []
Output: true
💡 Note: No prerequisites means all courses can be taken in any order. Always possible to complete.

Constraints

  • 1 ≤ numCourses ≤ 105
  • 0 ≤ prerequisites.length ≤ 5000
  • prerequisites[i].length == 2
  • 0 ≤ ai, bi < numCourses

Visualization

Tap to expand
Course Schedule - DFS Cycle Detection INPUT Dependency Graph 0 Course 0 1 Course 1 prereq numCourses = 2 prerequisites = [[1,0]] "Take 0 before taking 1" Adjacency List: 0: [] | 1: [0] Course 1 depends on 0 ALGORITHM STEPS 1 Build Graph Create adjacency list 2 Track Visit States 0=unvisited, 1=visiting, 2=done 3 DFS Each Course Detect cycles with state=1 4 Return Result No cycle = true DFS Traversal Visit 0 Done 0 Visit 1 Check prereq: 0 (Done) No cycle! Done 1 FINAL RESULT All Courses Completable 0 OK 1 OK Output: true Valid Course Order: Course 0 --> Course 1 No cyclic dependencies All courses can be finished Key Insight: Course scheduling is a topological sort problem. A valid schedule exists if and only if there are no cycles in the dependency graph. DFS with 3 states (unvisited, visiting, visited) detects cycles: if we encounter a node in "visiting" state during DFS, we found a back edge indicating a cycle. Time: O(V+E), Space: O(V+E) TutorialsPoint - Course Schedule | DFS Cycle Detection Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
67.5K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen