Skip to content
DSA in JavaScript
← All patterns

Topological Sort

0/10 solved

What it is

Order tasks so that every task comes after the ones it depends on. Repeatedly take a task with no remaining prerequisites.

Used for

Course schedules, build order, detecting cycles in dependencies.
task
A
B
C
D
waiting for
0
1
1
2
queue
·

Step 1 of 6

Goal: put tasks in an order where each comes after the ones it depends on. A→B, A→C, B→D, C→D means A before B and C, and both before D. Count how many things each task is still waiting for: its in-degree.

You see

  • Prerequisites or dependencies
  • Build or task ordering
  • Detect an impossible ordering (cycle)

Learn it in

Topological SortingDetect Cycle in Graphs

Template

function order(n, edges) { // Kahn's algorithm  const adj = Array.from({ length: n }, () => []), indeg = Array(n).fill(0);  for (const [a, b] of edges) { adj[a].push(b); indeg[b]++; }  const q = [...indeg.keys()].filter(i => !indeg[i]), out = [];  while (q.length) {    const u = q.shift(); out.push(u);    for (const v of adj[u]) if (--indeg[v] === 0) q.push(v);  }  return out.length === n ? out : []; // [] means a cycle}

Practice problems