Example 1
- Input
- numCourses = 2, prerequisites = [[1,0]]
- Output
- [0,1]
Course 0 has no prerequisites, so taking 0 then 1 respects the single dependency.
Given a course count and prerequisite pairs, return any order in which all courses can be finished, or an empty array when a cycle makes it impossible.
You are given numCourses courses labeled 0 to numCourses - 1 and prerequisites prerequisites[i] = [a, b] meaning course b comes before course a.
Return any ordering that respects every prerequisite, or an empty array when no such ordering exists.
1 <= numCourses <= 20000 <= prerequisites.length <= numCourses * (numCourses - 1)prerequisites[i].length == 20 <= a, b < numCoursesCourse 0 has no prerequisites, so taking 0 then 1 respects the single dependency.
After 0, courses 1 and 2 are both ready; either may come first. Course 3 must follow both. Thus [0,2,1,3] and [0,1,2,3] are equally valid outputs.
With no prerequisites the lone course stands alone in the order.
Courses 0 and 1 depend on each other. Course 2 is independently available, but finishing only it is insufficient: a full order is impossible, so return no order.
A prerequisite is a directed constraint: [1,0] says 0 must precede 1. A valid order exists exactly when these constraints have no directed cycle. You can finish a course after exploring all of its prerequisites, or repeatedly take a course whose unfinished prerequisite count is zero. The first strategy uses DFS finish order; the second uses a queue of ready courses. Multiple ready courses can be chosen in any order.
Reveal DFS Postorder: intuition, complexity, and code
[a, b] as a directed edge from b to a, since b must come first.numCourses, a cycle blocks the rest, so return the empty array.0 through numCourses - 1 in sequence.[0].[0, 0] can never be scheduled and must return [].When a problem asks for the order itself rather than just feasibility, emit nodes as their dependencies clear; Kahn construction turns cycle detection into ordering.