#207

Course Schedule

Medium Cycle detection with Kahn's algorithm

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

?The problem

Courses have prerequisite pairs [a, b] meaning b must come before a. Decide whether all courses can be finished.

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

◎Understanding

Really asking: can you finish all courses given their prerequisites (is there no cycle)?

Why this works: Kahn's algorithm keeps taking courses with no remaining prerequisites. If some courses are never taken, they sit on a cycle.

Example: 2 courses, [1 needs 0], [0 needs 1]

no course starts with 0 prerequisites → 0 taken → false

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Reversing the edge direction — it still detects cycles here, but gives the wrong order in Course Schedule II.

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