Advanced 12 min

Topological sorting

A topological order puts each prerequisite before the work that requires it.

How it works

Write the incoming-edge count beside each item. A and B are ready at count zero. Finishing A reduces C’s count from 2 to 1. Finishing B reduces it to 0, which allows C to run. Several valid orders can exist when multiple items are ready together.

Walk through an example

Count each node’s incoming edges. Start with nodes whose count is zero. When you remove one, subtract its outgoing edges and add any newly unblocked nodes.

What to watch for

A cycle prevents a complete topological order. If the available queue empties before you output every node, report a cycle.

Code example

incoming = {'A': 0, 'B': 0, 'C': 2}
ready = [node for node in incoming if incoming[node] == 0]
print(ready)

Check your understanding

Give one valid order.

See the example and explanation
Worked example
Given A → C and B → C
Answer A, B, C

Both A and B are available at the start. C becomes available after both predecessors are removed.

Open practice problem
Next lessonGreedy interval scheduling