InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Course Schedule II

medium Original ↗ 00:00

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.

The second example as a dependency graph, where an arrow means “must be taken before”:

flowchart TD
    C0["Course 0"] --> C1["Course 1"]
    C0 --> C2["Course 2"]
    C1 --> C3["Course 3"]
    C2 --> C3

Any order that lists every course after its prerequisites is valid, so both [0, 1, 2, 3] and [0, 2, 1, 3] work.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug