InterviewPrepKit

Home / Coding / Graphs

Course Schedule

medium Original ↗
Solving tips
  • Reframe as cycle detection on a directed graph: prerequisite [a,b] means edge b -> a ('b unlocks a'), and all courses are finishable iff the graph is acyclic.
  • Kahn's algorithm (BFS): compute in-degrees, queue the in-degree-0 courses, and decrement dependents as you take each; if the count taken equals numCourses there is no cycle.
  • DFS alternative uses three colors (white/gray/black) — reaching a GRAY node is a back edge (cycle); a plain visited set can't distinguish 'on stack' from 'finished' and misreports.
  • Both are O(V+E); watch the edge direction and note the long-chain (up to 2000) recursion-limit risk favors Kahn's.

Problem

There are numCourses courses labeled 0 to numCourses - 1. You’re given a list prerequisites where each entry [a, b] means “to take course a, you must first finish course b.”

Return True if it’s possible to finish every course, and False otherwise.

Finishing all courses is possible exactly when the prerequisite relation contains no circular dependency (you can’t have a needing b needing … needing a).

Examples

  • numCourses = 2, prerequisites = [[1,0]]True — take 0, then 1.
  • numCourses = 2, prerequisites = [[1,0],[0,1]]False — 1 needs 0 and 0 needs 1, a cycle.
  • numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]True — order 0, 1, 2, 3 works (0, 2, 1, 3 works too).

Constraints

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

Think about it first

Hint 1 Model courses as nodes and each prerequisite [a, b] as a directed edge b → a ("b unlocks a"). The question "can I finish everything?" becomes "does this directed graph have a cycle?"
Hint 2 Two classic cycle tests for a directed graph. (1) DFS with three states — unvisited / in the current recursion stack / fully done — where revisiting a node that's still on the stack is a back edge, i.e. a cycle. (2) Kahn's algorithm: repeatedly remove a node with no remaining prerequisites; if you can't remove all of them, the leftovers form a cycle.
Hint 3 For Kahn's: compute each course's in-degree (how many prerequisites it still has), start a queue with the in-degree-0 courses, and each time you "take" a course, decrement its dependents' in-degrees, enqueueing any that hit 0. If the number of courses taken equals numCourses, there's no cycle.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.