InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Course Schedule

medium Original ↗ 00:00

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.

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