TRT
Sign in
mediumAdvancedLeetCode#topological sort

Course schedule II

Return an order in which all courses can be taken, or an empty list if the prerequisites form a cycle.

The Runtime Theory Team1 min read
Taught inTopological sortPro — members onlyA topological order lists the vertices of a directed acyclic graph so that every edge points forward: everything comes after what it depends on. Kahn's algorithm builds one with in-degrees and a queue, and detects cycles for free.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innumCourses = 2, prerequisites = [[1, 0]]

out[0, 1]

innumCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]

out[0, 1, 2, 3] or [0, 2, 1, 3]

innumCourses = 1, prerequisites = []

out[0]

Same setting as Course schedule, but return one valid order of all courses, or an empty array if it is impossible.

Before you code

Kahn's algorithm already produces the order as it runs; the only extra step is returning it, or nothing if it came out short.

Hints

  1. Same graph and in-degrees as before.
  2. Append each dequeued course to the order.
  3. If the order has fewer than numCourses entries, return [].
  4. Try the DFS version too: reverse the finish order, and raise on a gray neighbor.

Production & complexity notes

When solving Course schedule II on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Topological sort to reinforce the underlying pattern.

What it practices

Producing a topological order, from Topological sort.

Not started

Sign in to save your learning progress.

Sign in to save