Dependencies form a directed graph: an edge b -> a means b must come before a. You can finish everything exactly when that graph has no cycle. Kahn's algorithm finds out by repeatedly removing nodes that have nothing left to wait for.
A degree has num_courses modules numbered 0 .. num_courses-1. Each pair [a, b] in prerequisites says that module b has to be passed before module a can be started. Write can_finish(num_courses, prerequisites) that returns True when some order lets a student pass every module, and False when the rules make that impossible.
Examples
Input: num_courses = 3, prerequisites = [[2, 0], [2, 1]]
Output: True
Explanation: take 0 and 1 (in either order), then 2
Input: num_courses = 3, prerequisites = [[2, 1], [1, 2]]
Output: False
Explanation: 0 is free, but 1 and 2 each wait for the other
Constraints
1 <= num_courses <= 20000 <= len(prerequisites) <= 5000, no duplicate pairs- Target: O(V + E) time
Goals
- Model prerequisites as a directed graph
- Detect a cycle in a directed graph with Kahn's algorithm (in-degree counting)
- Recognise that a topological order exists if and only if the graph is acyclic