LeetCode 207. Course Schedule
🧩 Problem Description
There are numCourses
courses labeled from 0
to numCourses - 1
.
You are given an array prerequisites
where prerequisites[i] = [a, b]
indicates that to take course a
you must first take course b
.
Return true
if you can finish all courses. Otherwise, return false
.
This is essentially asking whether the directed graph has a cycle. If there is no cycle, a topological ordering exists and you can finish all courses.
💬 Examples
Example 1
1 | Input: numCourses = 2, prerequisites = [[1,0]] |
Example 2
1 | Input: numCourses = 2, prerequisites = [[1,0],[0,1]] |
💡 Approach 1: Kahn’s Algorithm (BFS Topological Sort)
- Build adjacency list and in-degree array.
- Push all nodes with in-degree
0
into a queue. - Pop from queue, decrement in-degree of neighbors, and push any that drop to
0
. - If we process all nodes, there is no cycle; otherwise, a cycle exists.
🔢 Java Code (BFS)
1 | class Solution { |
💡 Approach 2: DFS Cycle Detection (3-color / visiting states)
- Maintain a
state[]
array:0 = unvisited
,1 = visiting
,2 = visited
. - During DFS, if we reach a node marked
visiting (1)
, we found a cycle. - If DFS finishes without back edges, there is no cycle.
🔢 Java Code (DFS)
1 | class Solution { |
⏱ Time and Space Complexity
- BFS (Kahn):
- Time: O(V + E)
- Space: O(V + E) for graph + queue + indegree
- DFS:
- Time: O(V + E)
- Space: O(V + E) for graph + recursion stack
V = numCourses
, E = len(prerequisites)
.
✍️ Summary
- The problem reduces to cycle detection in a directed graph.
- Kahn (BFS) is usually simplest when you just need a yes/no; it also gives a topo order.
- DFS 3-color is elegant and stack-based.
- Pick based on your preference and constraints.
Related problems
lc-210
— Course Schedule II (return topological order)lc-261
— Graph Valid Tree (undirected)lc-802
— Find Eventual Safe States