Skip to main content

LeetCode Patterns

Topological Sort Pattern

Topological Sort produces a linear ordering of the vertices in a directed acyclic graph such that for every edge u -> v, u appears before v in the order. It is the canonical pattern for dependency resolution, course scheduling, and build ordering problems, running in O(V + E) time using either Kahn's BFS algorithm or a DFS post-order traversal.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Complexity

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

When to use Topological Sort

  • The input describes dependencies between tasks, courses, items, or jobs ("X must come before Y").
  • You need to detect whether a directed graph contains a cycle.
  • You need a build order, install order, or compile order for an interlinked set of modules.
  • You need to schedule tasks subject to prerequisite constraints.
  • You need to reconstruct a partial order from a list of pairwise comparisons (alien dictionary).

Template

function topologicalSort(numNodes, edges) {
  const indegree = new Array(numNodes).fill(0);
  const graph = Array.from({ length: numNodes }, () => []);
  for (const [from, to] of edges) {
    graph[from].push(to);
    indegree[to]++;
  }
  const queue = [];
  for (let i = 0; i < numNodes; i++) {
    if (indegree[i] === 0) queue.push(i);
  }
  const order = [];
  while (queue.length > 0) {
    const node = queue.shift();
    order.push(node);
    for (const next of graph[node]) {
      if (--indegree[next] === 0) queue.push(next);
    }
  }
  return order.length === numNodes ? order : [];
}

Example LeetCode problems

#ProblemDifficultyFrequency
207Course Schedulemediumfoundational
210Course Schedule IImediumcompany favorite
269Alien Dictionaryhardcompany favorite
310Minimum Height Treesmediumfrequently asked
2115Find All Possible Recipes from Given Suppliesmediumclassic
444Sequence Reconstructionmediumless common
1136Parallel Coursesmediumfrequently asked

Common mistakes

  • Reversing the edge direction by mistake — the pattern needs `prerequisite -> course`, not the other way around (or vice versa, depending on the problem statement).
  • Returning a partial order when a cycle exists; the algorithm must detect that fewer than V nodes were emitted and return an empty result or signal failure.
  • Forgetting to initialize the indegree array to zero before counting, leaving undefined values in some languages.
  • Using DFS post-order without a visited-state machine (unvisited / in-progress / done), which both misses cycles and double-counts nodes.
  • Mutating the input edges list during processing, which makes the algorithm non-idempotent and breaks retry logic.

Frequently asked questions

What is the difference between Kahn's algorithm and DFS-based topological sort?

Kahn's repeatedly removes nodes with zero indegree and is naturally iterative — easier to reason about and to extend with cycle detection. DFS-based sort runs a post-order traversal and reverses the result; it is slightly less code but requires a 3-color visited state to detect cycles.

How does Topological Sort detect cycles?

In Kahn's algorithm, if the final order has fewer than V nodes, a cycle exists (no node ever reached indegree zero inside the cycle). In DFS, encountering a node currently in the recursion stack signals a back edge, which is a cycle.

Is the topological order unique?

Only if the graph is a single chain. In general, multiple valid orders may exist whenever two nodes have no path between them. Problems that ask for a specific ordering usually require lexicographic ties (smallest first) or all valid orderings.

What graphs does this pattern NOT work on?

Undirected graphs (no concept of "before") and directed graphs with cycles. Cycles must be either detected as a failure case or broken via SCC contraction before sorting.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill the Topological Sort pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →