Skip to main content

Topological Sort

What topological sort means, when order depends on dependencies, and why it shows up in graphs without looking like a graph problem at first.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

Topological sort means finding a valid order for executing or listing items with dependencies.

If A depends on B, then B must come before A.

When to use it

It appears when the problem talks about:

  • prerequisites
  • build order
  • dependency pipelines
  • tasks that must happen before other tasks

Common mistake

The classic mistake is expecting a single unique order.

There are often many valid orders.

The point is respecting dependencies, not finding the prettiest sequence.

Better question

Before using it, ask:

  1. is there a clear “must come before” relationship?
  2. does the problem break if I swap some items?
  3. can there be a cycle, and what would that mean here?

Keep exploring