Course Schedule
Master this topic with zero to advance depth.
Course Schedule
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.
Return true if you can finish all courses. Otherwise, return false.
Visual Representation
Courses: 2, Prerequisites: [[1, 0]]
Graph: 0 -> 1
Cycle? No. Result: true
Prerequisites: [[1, 0], [0, 1]]
Graph: 0 <-> 1 (Cycle!)
Cycle? Yes. Result: falseExamples
To take course 1 you should have finished course 0. So it is possible.
Level II: Intermediate (DFS - Cycle Detection)
Intuition
A graph is a Directed Acyclic Graph (DAG) if there are no Back Edges during DFS. We use three states for each node: 0 (unvisited), 1 (visiting/in current path), and 2 (visited). If we encounter a node with state 1, a cycle exists.
Thought Process
- Build an adjacency list.
- For each course, if not visited, launch DFS.
- In DFS:
- Mark node as
1(visiting). - Traverse neighbors. If a neighbor is in state
1, returnfalse(cycle). - Mark node as
2(fully processed).
- Mark node as
- If no cycle is found for any node, return
true.
Pattern: DFS Cycle Detection
Detailed Dry Run
pre=[[1,0],[0,1]]
| Node | State | Neighbors | Result |
|---|---|---|---|
| 0 | 1 | [1] | Launch DFS(1) |
| 1 | 1 | [0] | 0 is state 1! CYCLE! |
| Return | - | - | false |
Level III: Optimal (Kahn's Algorithm - BFS)
Intuition
Kahn's algorithm uses In-Degrees to peel off nodes with no dependencies. This is the gold standard for Topological Sort as it's iterative and avoids recursion stack issues.
Thought Process
- Calculate the in-degree of each course (number of prerequisites).
- Add all courses with
in-degree == 0to a queue. - While the queue is not empty:
- Pop a course, increment
completedcount. - For each course that depends on it, decrement its in-degree.
- If in-degree becomes 0, add to queue.
- Pop a course, increment
- If
completed == numCourses, returntrue.
Pattern: Topological Sort
Detailed Dry Run
num=2, pre=[[1,0]]
| Pop | Queue | In-Degrees | Count |
|---|---|---|---|
| - | [0] | [0:0, 1:1] | 0 |
| 0 | [1] | [1:0] | 1 |
| 1 | [] | - | 2 |
| Result: 2 == 2 (True) |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.