codebrew.ai

Course Schedule

You can finish all courses iff the prerequisite graph has no cycle.

Approach

Model courses as a directed graph of prerequisites. Run Kahn's algorithm: repeatedly remove nodes with in-degree zero; if you can remove all of them, there's a valid order, otherwise a cycle blocks completion. A DFS with a recursion-stack cycle check works too.

Time complexity

O(V + E)

Space complexity

O(V + E)

Common mistake

Conflating 'visited' with 'in the current DFS path' — cycle detection needs the on-stack state, not just visited.

See it run, step by step

Generate an interactive lesson for Course Schedule — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Course Schedule

Related problems