Skip to content
DSA Patterns
Menu
Language
Topological SortLC #2071 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Course Schedule

Problem (restated)

n courses with prereq pairs [a,b] meaning b before a. Return whether you can finish all.

Intuition

Detect cycle in directed graph via topo sort; if order length < n, cycle.

Approaches

Kahn BFS

Unverified
Time O(V+E)Space O(V+E)

Idea. Indegree queue Kahn; count taken courses.

Walkthrough. [[1,0]] n=2 → true; cycle → false.

Trade-offs. Kahn vs DFS colors.

Solution
export function canFinish(numCourses: number, prerequisites: number[][]): boolean {
  const g: number[][] = Array.from({ length: numCourses }, () => []);
  const indeg = new Array(numCourses).fill(0);
  for (const [a, b] of prerequisites) {
    g[b!]!.push(a!);
    indeg[a!]++;
  }
  const q: number[] = [];
  for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) q.push(i);
  let head = 0;
  let taken = 0;
  while (head < q.length) {
    const u = q[head++]!;
    taken++;
    for (const v of g[u]!) {
      if (--indeg[v]! === 0) q.push(v);
    }
  }
  return taken === numCourses;
}
export function canFinish(numCourses: number, prerequisites: number[][]): boolean {
  const g: number[][] = Array.from({ length: numCourses }, () => []);
  const indeg = new Array(numCourses).fill(0);
  for (const [a, b] of prerequisites) {
    g[b!]!.push(a!);
    indeg[a!]++;
  }
  const q: number[] = [];
  for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) q.push(i);
  let head = 0;
  let taken = 0;
  while (head < q.length) {
    const u = q[head++]!;
    taken++;
    for (const v of g[u]!) {
      if (--indeg[v]! === 0) q.push(v);
    }
  }
  return taken === numCourses;
}

Template connection

Kahn: queue every course with indegree 0, then pop it and reduce its neighbors. Popping numCourses nodes means there is no cycle.

Reflection

  • The edge runs from prerequisite to course. Kahn puts indegree 0 on the queue. If fewer than n nodes leave the queue, there is a cycle and the answer is false.
  • [[0,1],[1,0]] is a cycle. No edges is true. Counting the same prerequisite twice inflates the indegree.
  • A colored DFS that returns to a gray node is the same cycle. Both methods agree.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Course Schedule: n=3, prereqs [1,0] and [2,1] mean 0 before 1 before 2. Finish all iff the digraph is a DAG.

0in 01in 12in 1

edge b→a ⇔ b before a

Key:CurrentActive rangeSettledEliminated