#210

Course Schedule II

Medium Topological sort (Kahn)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Same prerequisites as Course Schedule. Return any valid order to take all courses, or an empty array if impossible.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: give a valid order to take all courses.

Why this works: the order in which Kahn's algorithm removes courses is a topological order.

Example: 4 courses, 1 and 2 need 0, 3 needs 1 and 2

take 0 → then 1, 2 → then 3 → [0, 1, 2, 3]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning a partial order when a cycle exists — return an empty array instead.

Solve on LeetCode ↗
Complexity
  • Time: O(V + E).
  • Space: O(V + E).
Topic: Graphs
🎬 Episodes 74–85: video coming soon