Graph Theory37 sections · 1633 units
Open in Course

Course Schedule II - The Constraint

Building dependencies

Each prerequisite pair [a,b][a, b] means "course bb must be taken before course aa". This creates a directed edge bab \to a in your graph. If you have [0,1][0, 1] and [1,2][1, 2], the graph looks like 2102 \to 1 \to 0. You must take course 22 first, then 11, then 00. The order respects all dependencies.

What if you have [0,1][0, 1] and [1,0][1, 0]? Course 00 needs 11 first, and course 11 needs 00 first. That is 0100 \to 1 \to 0, a cycle. No valid ordering exists, so you return an empty array. Building the adjacency list and in-degree array from the input pairs is the first step before running Kahn's algorithm.