Skip to content
ΣDSA Patterns
Menu
Language

Topological Sort

Guide 1 of 6 · Path 1 of 6

PreviousNext →

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
0in 01in 12in 1

edge b→a ⇔ b before a

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

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 taken = 0;
  while (q.length) {
    const u = q.shift()!;
    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 taken = 0;
  while (q.length) {
    const u = q.shift()!;
    taken++;
    for (const v of g[u]!) {
      if (--indeg[v]! === 0) q.push(v);
    }
  }
  return taken === numCourses;
}

Template connection

Topological sort cycle detect.

Reflection