#207

Course Schedule

MediumTopological SortHas vizDFSBFSGraphTopological Sort

Problem

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

Return true if you can finish all courses. Otherwise, return false.

Example 1

Input: numCourses = 2, prerequisites = [[1,0]]

Output: true

Take 0 then 1.

Example 2

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]

Output: false

Cycle between 0 and 1.

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.
Loading visualization…

Explanation

Course Schedule is a Medium interview problem tagged [DFS, BFS, Graph, Topological Sort]. The winning approach is typically **Topological Sort**.

Intuition

Dependency edges define a partial order you must respect.

Approach

Kahn (indegree queue) or DFS finish-order on a DAG; detect cycles if not all nodes ordered.

  1. Build indegrees.
  2. Queue zeros.
  3. Reduce neighbors.
  4. Fail if processed < n.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateTopological Sort

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Topological Sort), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #207 Course Schedule as understood when the pattern clicks.