Skip to main content
Back to all problems
Beginner guide, Algorithms & data structures

Advanced Graphs

Topological sort: an order that respects dependencies, when the graph itself is hidden in the input.

This category builds on the Graphs guide (read that first). It covers graph algorithms with a name of their own. The one used here is topological sort: putting things in an order that respects their dependencies.

The problem topological sort solves

You have tasks, and some must happen before others: "compile utils before app", "take Algebra before Calculus", "the letter t comes before f". Draw each rule as an arrow before → after:

Loading diagram...

A topological order lists every node so that every arrow points forward. Here, socks, pants, shoes, belt works, and so does pants, belt, socks, shoes. There can be many valid orders.

It's only possible when the graph has no cycle. If a → b → a, neither can go first.

Kahn's algorithm (BFS)

The in-degree of a node is how many arrows point into it: how many things must happen before it.

js
// inDegree[x]: number of arrows into x. next[x]: nodes x points to.
const queue = nodes.filter((x) => inDegree[x] === 0) // nothing blocks these
const order = []
for (let i = 0; i < queue.length; i++) {
  const x = queue[i]
  order.push(x)
  for (const y of next[x]) {
    inDegree[y]-- // x is done: one less thing blocking y
    if (inDegree[y] === 0) queue.push(y) // y is free now
  }
}
// order.length < number of nodes → there was a cycle
  1. Start with every node nothing points to.
  2. Take one, add it to the order, and remove its outgoing arrows.
  3. Anything that now has nothing pointing to it is free: queue it.
  4. If some nodes were never freed, they're on a cycle.

It does two jobs at once: it finds an order, and it detects cycles.

Building the graph is often the real work

Problems rarely hand you the arrows directly. In Alien Dictionary, you have to work out the rules from sorted words first, and the details matter:

  • Every node must be in the graph, even ones with no rules (in-degree 0), or they'll be missing from the answer.
  • Don't add the same arrow twice, or an in-degree is too high and that node is never freed. Store successors in a set.
  • Watch for inputs that are invalid on their own, before any sorting.

Other algorithms in this family

You won't need these for the problems here, but they're worth knowing by name:

AlgorithmWhat it does
Dijkstrashortest path when edges have weights (distances, costs), using a min-heap
Bellman-Fordshortest path when some weights are negative
Prim / Kruskalminimum spanning tree: connect all nodes as cheaply as possible (Kruskal uses Union-Find)
Union-Findtracks groups and detects cycles while edges are added (see Graphs)

How to recognize topological sort

  • "In what order...", "is it possible to finish...", "build order", "dependencies", "prerequisites".
  • A list of "A before B" relationships, given directly or hidden in the input (like a sorted list).
  • If the question is only "is it possible?", you're detecting a cycle; if it's "what order?", you return the order.

Common mistakes

  • Arrows in the wrong direction. Decide "before → after" and stick to it.
  • Forgetting isolated nodes (no arrows in or out).
  • Duplicate arrows inflating in-degrees.
  • Returning a partial order when there's a cycle, instead of reporting that it's impossible.

Practice what you learned

The problems go from easier to harder. Try each one on your own and open a hint when you get stuck.