Course Schedule II
Master this topic with zero to advance depth.
Course Schedule II
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 the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Visual Representation
Prerequisites: [[1, 0], [2, 0], [3, 1], [3, 2]]
Graph:
0 -> 1 -> 3
0 -> 2 -> 3
Possible Order: [0, 1, 2, 3] or [0, 2, 1, 3]Examples
To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
Level II: Intermediate (DFS - Post-order)
Intuition
In a DAG, if we perform DFS and record nodes in Post-order (after visiting all neighbors), and then reverse that list, we get a topological sort. We must also check for cycles using the recursion stack.
Thought Process
- Build adjacency list.
- Use a
visitedset to track globally visited nodes and apath(recursion stack) set for cycle detection. - In DFS(u):
- If
uinpath, returnFalse(cycle found). - If
uinvisited, returnTrue(already processed). - Add
utopathandvisited. - DFS neighbors. If any fails, return
False. - Remove
ufrompathand appenduto a Result List.
- If
- Call DFS for all unvisited nodes. Reverse the result list.
Pattern: DFS Topological Sort
Detailed Dry Run
num=2, pre=[[1,0]]
| Call | Path | Result | Action |
|---|---|---|---|
| DFS(0) | {0} | [] | Visit 1 |
| DFS(1) | {0,1} | [1] | No neighbors, backtrack |
| - | {0} | [1,0] | Done with 0 |
| Reverse [1,0] -> [0,1] |
Level III: Optimal (Kahn's Algorithm - BFS)
Intuition
Kahn's algorithm uses the concept of in-degrees (number of incoming edges). Nodes with 0 in-degree are ready to be taken. We repeatedly take such nodes and 'remove' their outgoing edges, potentially creating new 0 in-degree nodes.
Thought Process
- Calculate
indegreefor all nodes. - Add all nodes with
indegree == 0to a Queue. - While queue is not empty:
- Pop
u, add it to theresultlist. - For each neighbor
vofu:- Decrement
indegree[v]. - If
indegree[v] == 0, addvto queue.
- Decrement
- Pop
- If
resultlength ==numCourses, return it; otherwise, a cycle exists.
Pattern: Topological Sort (BFS)
Detailed Dry Run
2 courses, 1 -> 0
- Indegrees: {0:1, 1:0}
- Queue: [1]
- Pop 1, Res: [1], Indegree 0 becomes 0, Queue [0]
- Pop 0, Res: [1, 0] Result: [1, 0]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.