Maintained by Vikas Dulgunde, software engineer
You have a set of courses numbered from 0 up to numCourses minus 1. Each entry in the prerequisites list is a pair [a, b] that says course b has to be done before course a. The pairs together describe which courses unlock which.
Your job is to report whether a full ordering of all the courses exists. That ordering is only possible when no course ends up, directly or through a chain, depending on itself.
If you picture each course as a point and each prerequisite as an arrow from the earlier course to the later one, the whole thing is a directed graph. Finishing every course is feasible exactly when that graph has no cycle.
Return true when all courses are reachable in some valid order, and false when a cycle makes that impossible.
Course 0 has no prerequisite, so take it first, then course 1. Both finish, so the answer is true.
Course 1 needs course 0 and course 0 needs course 1. Neither can start, which is a cycle, so the answer is false.
Course 0 unlocks 1 and 2, which in turn unlock 3 and 4. The dependencies branch out without ever looping back, so all five courses complete.
Visible test cases
Model the courses as nodes and each pair [a, b] as a directed edge from b to a. The question becomes: does this directed graph contain a cycle?
A course with no remaining unmet prerequisites can be taken right away. Track how many prerequisites each course still has using an in-degree count.
Repeatedly take every course whose in-degree is 0, then reduce the in-degree of the courses it unlocks. If you manage to take all of them, there was no cycle.
Walk the dependency graph with depth-first search and look for a node that appears again on the current path, which signals a cycle.
Peel off courses that have no outstanding prerequisites one layer at a time. If you can remove every course this way, the graph is acyclic.