We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium topological sort problem, graded against 6 test cases (3 of them hidden).
Ordering a directed acyclic graph so every dependency comes first.
Reach for it when you see: Prerequisites, build order, task scheduling, or "can this be completed?"
More Topological Sortproblems →Edges point from prerequisite to dependent (`b -> a`), and a course's indegree is the number of prerequisites it still needs. Courses with indegree 0 are takeable now.
Kahn's algorithm repeatedly removes an available course, appends it to the order, and decrements the indegree of everything it unlocks, adding newly-freed courses to the available set. Each edge is relaxed exactly once, so it is linear.
Cycle detection is free. If a cycle exists, every course in it keeps a positive indegree forever and never becomes available, so the loop ends early. Comparing the produced order's length against `numCourses` is the whole check - no separate DFS colouring pass.
Normally any topological order is acceptable, which makes the answer non-unique. The lowest-numbered tie-break pins it down: swap the FIFO queue for a min-heap so the smallest available course is always chosen. That is a common real-world requirement too, where builds want a reproducible order rather than merely a valid one.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.