InterviewPrepKit

Home / Coding / Graphs

Course Schedule II

medium Original β†—
Solving tips
  • Recognize this as topological sort: same graph as Course Schedule (edge b -> a for [a,b]), now outputting an actual order that exists iff the graph is acyclic.
  • Kahn's BFS builds the answer directly β€” append each course as its in-degree hits 0; if fewer than numCourses come out, a cycle trapped the rest, so return [].
  • DFS alternative: append nodes at finish time (post-order) then REVERSE the list; forgetting the reverse gives the opposite (invalid) order.
  • Both O(V+E); return the empty-list sentinel on a cycle rather than a partial order, and mind the edge direction.

Problem

There are numCourses courses labeled 0 to numCourses - 1. Each prerequisites[i] = [a, b] means course b must be taken before course a.

Return any valid order in which you can take all the courses. If no valid order exists (a circular dependency makes it impossible), return the empty list [].

This is Course Schedule I, but instead of a yes/no you must produce an actual ordering.

Examples

  • numCourses = 2, prerequisites = [[1,0]] β†’ [0, 1] β€” 0 has no prerequisite, and 1 needs 0.
  • numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] β†’ [0, 1, 2, 3] β€” 0 first, then 1 and 2 (either order), then 3. [0, 2, 1, 3] is equally valid.
  • numCourses = 1, prerequisites = [] β†’ [0] β€” one course, nothing blocks it.
  • numCourses = 2, prerequisites = [[1,0],[0,1]] β†’ [] β€” cyclic, impossible.

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= len(prerequisites) <= numCourses * (numCourses - 1)
  • Each prerequisites[i] is a pair of distinct labels; no duplicate pairs.

Think about it first

Hint 1 Same graph as Course Schedule: edge b β†’ a for each [a, b]. You now need to output a linear ordering that respects every edge β€” a topological sort. It exists iff the graph is acyclic.
Hint 2 Kahn's algorithm builds the order directly: courses become "ready" the moment their in-degree hits 0. Append each course to the answer as you take it. If a cycle blocks some courses, you'll take fewer than numCourses β€” detect that and return [].
Hint 3 DFS alternative: the reverse of a DFS post-order (finish order) is a valid topological order. Add three-color cycle detection so you can bail out with [] when a back edge appears.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.