Course outline

Data Structures & Algorithms / Ordered structures and graph reasoning / Lesson 14

Topological ordering and cycle detection

Order a directed acyclic graph by dependencies and detect when a cycle prevents a complete order.

About 18 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Define edge direction and indegree.
  • Explain why zero-indegree vertices can be selected.
  • Detect cycles and verify dependency order.
  • Prove the remaining-indegree invariant and diagnose incomplete output.
  • Verify any proposed order against vertex coverage and edge constraints.

Define dependency direction

A topological order places every source before its destination in a directed graph. Here an edge from design to build means design must precede build. A directed cycle makes such an order impossible because every vertex in the cycle would need to precede itself indirectly. The graph mapping in this example must contain every vertex as a key, including vertices with no outgoing edges.

Remove ready vertices

The algorithm counts incoming edges, then puts all zero-indegree vertices in a queue. Removing one vertex satisfies its outgoing dependencies; decrement each neighbor’s count and enqueue it when the count reaches zero. The invariant is that the queue contains vertices whose remaining incoming edges have been removed. If fewer vertices are output than exist in the graph, a cycle prevents completion and the function returns None.

python Order a directed graph
from collections import deque

def topological_order(graph):
    indegree = {node: 0 for node in graph}
    for neighbors in graph.values():
        for neighbor in neighbors:
            indegree[neighbor] += 1
    ready = deque(node for node, degree in indegree.items() if degree == 0)
    order = []
    while ready:
        node = ready.popleft()
        order.append(node)
        for neighbor in graph[node]:
            indegree[neighbor] -= 1
            if indegree[neighbor] == 0:
                ready.append(neighbor)
    return order if len(order) == len(graph) else None

Indegrees track unsatisfied incoming edges; an incomplete output signals a cycle.

Exercise an order and a cycle

The assertions use the function from the first block in the same Python file. The chain has one valid order; the two-node cycle returns None; an empty graph has an empty order. Other graphs can have several valid orders, so a general test should check every edge constraint and include every vertex once rather than comparing only one expected sequence. Duplicate edges should be represented and counted consistently.

python Check a chain and cycle
graph = {"design": ["build"], "build": ["test"], "test": []}
assert topological_order(graph) == ["design", "build", "test"]
assert topological_order({"a": ["b"], "b": ["a"]}) is None
assert topological_order({}) == []

The chain is ordered, the cycle is rejected, and the empty graph succeeds.

Analyze cost and contracts

Building indegrees and processing edges takes O(V + E) time and O(V) auxiliary space for V vertices and E stored edges, excluding the input graph. A neighbor absent from the mapping violates this example’s input contract and raises an error rather than silently creating a vertex. Decide whether a production API should validate and report that condition explicitly. A partial output is not a complete schedule when a cycle exists.

Verify against dependency constraints

Test disconnected components, multiple ready vertices, a self-loop, a longer cycle, and an edge to a missing key. For every successful result, build a position map and verify position[source] is less than position[destination] for each edge. Verify that each vertex appears exactly once. Compare small graphs against a simple reference, and do not interpret one valid order as the only possible order.

Model dependencies as directed constraints

A topological order is a sequence containing every represented vertex exactly once such that for every edge u→v, u appears earlier than v. Decide what an edge means before constructing the graph. Under the baseline convention u is a prerequisite of v, so reversing an edge changes the required order. Independent vertices need no relative order unless the application adds another constraint. Isolated vertices still belong in a complete result even though no edge mentions them.

The input mapping stores outgoing neighbors. Each destination must also be a key, including a sink with an empty list; otherwise the baseline indegree lookup raises an error. If repeated edges are allowed, count each occurrence when building indegrees and decrement each occurrence when removing its source. Alternatively normalize duplicates before both stages. Mixing these policies can leave a vertex falsely blocked or enqueue it too early. A fixed graph snapshot is assumed during the calculation.

Follow the actual queue implementation

The baseline Python function initializes each represented indegree to zero, scans every neighbor occurrence and increments its destination, then constructs a deque of zero-indegree vertices. Removing the leftmost ready vertex appends it to the output and subtracts one for every outgoing occurrence. When a neighbor count reaches zero it joins the queue. The count always represents incoming edges from vertices not yet removed; an edge from a processed vertex has already been subtracted. Thus every emitted vertex has no unsatisfied predecessor remaining.

For A→C and B→C, both A and B start ready while C has indegree two. Removing A reduces C to one, so C is still blocked. Removing B reduces it to zero, making C ready. Depending on the order in which A and B are selected, either A,B,C or B,A,C is valid. deque provides FIFO behavior for this implementation; it does not make the mathematical order unique. A priority queue may choose a reproducible smallest ready label, with additional ordering and cost assumptions.

Prove success and detect obstruction

Every emitted vertex has no incoming edge from the remaining graph. All its predecessors have therefore appeared earlier, so appending it preserves every dependency involving that vertex. If the output contains every vertex, each appears once and every edge points forward; the result is a topological order. Conversely a nonempty directed acyclic graph has a zero-indegree vertex: following incoming edges forever in a finite graph would repeat a vertex and create a directed cycle. Repeated removal therefore cannot stall in a DAG.

If the ready queue empties while vertices remain, every remaining vertex has an incoming edge from another remaining vertex. Following these edges in the finite remainder eventually repeats a vertex, proving a cycle. The baseline compares the processed count with the number of keys and returns None rather than presenting the prefix as a complete order. Remaining vertices are not necessarily all cycle members: a vertex downstream from a cycle may also remain blocked. Finding a particular cycle needs a separate witness procedure such as DFS active-path tracking.

Compare DFS and ordering policies

A DFS alternative marks vertices active on entry and finished after all outgoing edges have been scanned. An edge to an active ancestor closes a directed cycle; an edge to a finished vertex alone does not. In a DAG, reversing the order in which a full DFS forest finishes its vertices gives a topological order: for every edge u→v, v finishes before u, whether v is explored from u or was already finished. The full forest matters because a traversal from one root can omit disconnected vertices.

Kahn removal and reverse DFS finish can return different valid sequences because ready or neighbor order resolves choices. Neither inherently describes execution duration, concurrency limits, retries or transactional completion. A dependency order is a precedence constraint, not by itself an operational scheduler. If readiness is used for actual jobs, decrement dependencies only after the required predecessor completion event, and define failure and retry policies separately.

Validate results and account for work

For a proposed sequence first check its length and that its set equals the represented vertex set; duplicate or missing vertices invalidate it. Build a position map and verify position[u] < position[v] for every edge occurrence. This property-based check accepts all valid orders instead of assuming the queue produced one exact sequence. For small graphs, enumerate permutations as an independent finite oracle: a DAG has at least one satisfying sequence, while a cycle has none.

Counting indegrees and processing each stored edge occurrence once takes O(V+E) time with adjacency lists and expected constant-time map operations, plus O(V) auxiliary storage for counts, queue and result. Sorting ready vertices or using a heap changes that accounting. Test an empty graph, isolated vertices, converging prerequisites, duplicate edges, a self-loop, a longer cycle and an unknown endpoint. These synthetic cases support the proof but neither execute a real scheduler nor establish performance under production workloads.

20 worked examples

1. Direction

Problem: Interpret edge design→build as a dependency.

  1. The source design is the prerequisite.
  2. The destination build must occur after design.
text Synthetic trace
design→build
order: design, build

The destination build must occur after design.

Expected result: order: design, build

Why this result follows: The edge points from prerequisite to dependent.

2. Chain

Problem: Order A→B→C according to the directed edges.

  1. A is the only initial zero-indegree vertex.
  2. Removing A enables B, then removing B enables C.
text Synthetic trace
A→B→C
order: A,B,C

Removing A enables B, then removing B enables C.

Expected result: order: A,B,C

Why this result follows: Every chain edge forces its source before its destination.

3. Independent vertices

Problem: List possible orders of two isolated vertices A and B.

  1. Neither vertex has an incoming constraint.
  2. Either vertex can be first, so both permutations are valid.
text Synthetic trace
A: []; B: []
orders: A,B or B,A

Either vertex can be first, so both permutations are valid.

Expected result: orders: A,B or B,A

Why this result follows: No edge imposes a relative order on these vertices.

4. Converging prerequisites

Problem: Order P→T and Q→T according to the directed edges.

  1. P and Q are initially ready while T has two incoming edges.
  2. Both must be removed before T can become ready.
text Synthetic trace
P→T; Q→T
orders: P,Q,T or Q,P,T

Both must be removed before T can become ready.

Expected result: orders: P,Q,T or Q,P,T

Why this result follows: T must follow both of its prerequisites.

5. Indegrees

Problem: Count indegrees for A→B, A→C, B→C.

  1. A has no incoming edge; B receives one from A.
  2. C receives one each from A and B, giving two.
text Synthetic trace
A→B; A→C; B→C
indegree: A=0,B=1,C=2

C receives one each from A and B, giving two.

Expected result: indegree: A=0,B=1,C=2

Why this result follows: Each incoming edge occurrence contributes one to its destination.

6. Queue decrement

Problem: In A→B, B→C, trace readiness after removing A.

  1. Initially only A has indegree zero.
  2. Removing A lowers B from one to zero and enqueues B.
text Synthetic trace
A→B→C
after A: ready=[B]

Removing A lowers B from one to zero and enqueues B.

Expected result: after A: ready=[B]

Why this result follows: Removing the prerequisite satisfies its outgoing edge.

7. Disconnected components

Problem: Find one order for A→B and X→Y.

  1. The two chains impose no constraints on each other.
  2. A,X,B,Y satisfies A before B and X before Y.
text Synthetic trace
A→B; X→Y
valid: A,X,B,Y

A,X,B,Y satisfies A before B and X before Y.

Expected result: valid: A,X,B,Y

Why this result follows: Interleaving independent components preserves each edge constraint.

8. Empty graph

Problem: Find the topological order of an empty graph.

  1. There are no vertices to enqueue or emit.
  2. The processed count equals the zero vertex count, so the result is [].
text Synthetic trace
graph={}
order=[]

The processed count equals the zero vertex count, so the result is [].

Expected result: order=[]

Why this result follows: The empty sequence satisfies every nonexistent constraint.

9. Self-loop

Problem: Analyze a single vertex A with edge A→A.

  1. The loop gives A indegree one.
  2. No vertex is ready and the processed count is zero rather than one.
text Synthetic trace
A→A
result: None

No vertex is ready and the processed count is zero rather than one.

Expected result: result: None

Why this result follows: A cannot precede itself in a strict order.

10. Two-vertex cycle

Problem: Analyze A→B and B→A for topological ordering.

  1. Both vertices have indegree one.
  2. Neither can be selected first, so the algorithm returns None.
text Synthetic trace
A→B; B→A
result: None

Neither can be selected first, so the algorithm returns None.

Expected result: result: None

Why this result follows: The two constraints require each vertex to precede the other.

11. Blocked downstream

Problem: Analyze A→B, B→A and B→C after queue removal stops.

  1. A and B form a directed cycle with no initial ready vertex.
  2. C is blocked by B but has no edge returning to the cycle.
text Synthetic trace
A→B; B→A; B→C
remaining: A,B,C; cycle members: A,B

C is blocked by B but has no edge returning to the cycle.

Expected result: remaining: A,B,C; cycle members: A,B

Why this result follows: A downstream vertex can remain without itself belonging to a cycle.

12. Duplicate edges

Problem: Count and remove two stored A→B edge occurrences.

  1. The two occurrences give B indegree two.
  2. Removing A decrements B twice, reaching zero exactly once.
text Synthetic trace
A: [B,B]; B: []
indegree B: 2→1→0

Removing A decrements B twice, reaching zero exactly once.

Expected result: indegree B: 2→1→0

Why this result follows: Matching increments and decrements preserves the remaining-edge count.

13. Missing key

Problem: Diagnose {A:[B]} when B is absent from graph keys.

  1. The indegree dictionary contains only A.
  2. Incrementing indegree[B] raises KeyError under the baseline contract.
text Synthetic trace
graph={A:[B]}; keys={A}
missing: B

Incrementing indegree[B] raises KeyError under the baseline contract.

Expected result: missing: B

Why this result follows: Every edge destination must be represented before counting.

14. Alternative orders

Problem: Check A,B,C and B,A,C for only edges A→C and B→C.

  1. Both sequences place A before C.
  2. Both also place B before C and include every vertex once.
text Synthetic trace
A→C; B→C
valid: A,B,C and B,A,C

Both also place B before C and include every vertex once.

Expected result: valid: A,B,C and B,A,C

Why this result follows: Independent prerequisites can exchange positions. for this specific graph.

15. Invalid order

Problem: Check proposed order B,A,C against edge A→B.

  1. The position of A is one and the position of B is zero.
  2. The required inequality position[A] < position[B] fails.
text Synthetic trace
edge A→B; order B,A,C
invalid: 1 < 0 is false

The required inequality position[A] < position[B] fails.

Expected result: invalid: 1 < 0 is false

Why this result follows: One backward edge disproves a proposed order.

16. Reverse finish

Problem: Find DFS reverse finish order for A→B→C.

  1. DFS started at A finishes C, then B, then A.
  2. Reversing C,B,A produces A,B,C.
text Synthetic trace
finish: C,B,A
reverse: A,B,C

Reversing C,B,A produces A,B,C.

Expected result: reverse: A,B,C

Why this result follows: Every chain destination finishes before its source.

17. DFS back edge

Problem: Classify C→A while the DFS active path is A→B→C.

  1. The active stack contains the path from A to C.
  2. The edge C→A closes the directed cycle A→B→C→A.
text Synthetic trace
active: A→B→C; edge C→A
cycle: A→B→C→A

The edge C→A closes the directed cycle A→B→C→A.

Expected result: cycle: A→B→C→A

Why this result follows: An active-ancestor edge closes the current directed path.

18. Unique chain order

Problem: Determine whether A→B→C admits another complete order.

  1. A must precede B and B must precede C.
  2. Transitivity forces A before C as well, leaving only A,B,C.
text Synthetic trace
A→B→C
only order: A,B,C

Transitivity forces A before C as well, leaving only A,B,C.

Expected result: only order: A,B,C

Why this result follows: The chain constrains every pair of its vertices.

19. Mutation during traversal

Problem: Why is adding edge B→A after A was emitted unsafe?

  1. The emitted prefix assumed the earlier snapshot had no such prerequisite.
  2. The new edge requires B before A, which the existing output has already violated.
text Synthetic trace
old output: [A]; new edge B→A
prefix invalid for new graph

The new edge requires B before A, which the existing output has already violated.

Expected result: prefix invalid for new graph

Why this result follows: Changing constraints invalidates prior readiness decisions.

20. Verify coverage

Problem: Check order A,B,B for graph keys A,B,C with edge A→B.

  1. The sequence repeats B and omits represented vertex C.
  2. Although A appears before B, the sequence is not a complete topological order.
text Synthetic trace
keys={A,B,C}; order=[A,B,B]
invalid: duplicate B, missing C

Although A appears before B, the sequence is not a complete topological order.

Expected result: invalid: duplicate B, missing C

Why this result follows: Edge checks alone cannot establish vertex coverage.

Common errors and fixes

Dependencies execute backward

Why it happens
The edge direction was interpreted inconsistently.
How to fix it
Define whether an edge means prerequisite to dependent and use that convention throughout.
Prevent it next time
Test a two-vertex dependency with a known order.

A partial order is reported as complete

Why it happens
The algorithm did not compare processed and total vertex counts.
How to fix it
Reject the result when a cycle leaves vertices unprocessed.
Prevent it next time
Test a self-loop and a multi-vertex cycle.

A valid alternative order fails a test

Why it happens
The test assumes one exact ordering when several are valid.
How to fix it
Assert vertex coverage and every edge constraint.
Prevent it next time
Include disconnected and independent vertices.

20 practice exercises

1. Why can a zero-indegree vertex be placed next?

Show hint

Consider incoming edges from vertices still in the graph.

Show worked solution

No remaining edge requires another unprocessed vertex to precede it. Removing it and its outgoing edges maintains the dependency invariant for the remaining graph.

A zero-indegree vertex has no unsatisfied incoming edge from the remaining vertices. Placing it next cannot violate a remaining prerequisite; removing its outgoing edges updates the counts for subsequent choices.

Check your solution

  • No remaining predecessor must precede the chosen vertex.
  • Its outgoing edge occurrences are decremented once.

2. Can a directed cycle have a topological order?

Show hint

Follow the precedence inequalities around the cycle.

Show worked solution

No. Following its edges would require each vertex to appear before the next and eventually before itself. The processed-count check detects that no complete order was produced.

A directed cycle would require its first vertex to precede the next, and eventually to precede itself. A strict sequence cannot satisfy that requirement, so Kahn removal cannot emit every cycle vertex.

Check your solution

  • The cycle requires a vertex to precede itself indirectly.
  • The baseline returns None when the processed count is incomplete.

3. Convert “compile before package; package before release” into directed edges.

Show hint

Use prerequisite→dependent.

Show worked solution

The edges are compile→package and package→release. They require the sequence compile, package, release; reversing either edge would express a different dependency.

Check your solution

  • There are two edges.
  • Compile precedes release by transitivity.

4. A graph encodes deploy→test but testing must precede deployment. Repair the edge.

Show hint

Put the prerequisite at the source.

Show worked solution

Replace deploy→test with test→deploy. A valid order then places test before deploy; keeping both edges would instead create a two-vertex directed cycle.

Check your solution

  • The repaired edge is test→deploy.
  • Keeping both directions creates a cycle.

5. A directed graph has indegrees 0, 1, 2 and 3. How many edge occurrences does it contain?

Show hint

Each edge contributes to exactly one destination indegree.

Show worked solution

Summing the indegrees gives 0+1+2+3=6 edge occurrences. This identity holds with parallel edges when each occurrence is counted; it does not determine the exact source of each edge.

Check your solution

  • The indegree sum is 6.
  • The edge occurrence count is 6.

6. Trace the FIFO ready queue for P→R, Q→R with initial ready order P,Q.

Show hint

Enqueue R only when its remaining count reaches zero.

Show worked solution

The queue starts [P,Q]. Removing P leaves [Q] and R has one incoming edge; removing Q enqueues R, yielding [R]. Removing R completes P,Q,R.

Check your solution

  • Queue states are [P,Q], [Q], [R], [].
  • The result is P,Q,R.

7. Construct a four-vertex DAG with exactly four topological orders.

Show hint

Use a three-vertex chain and one isolated vertex.

Show worked solution

Take A→B→C and isolated D. The chain must stay A,B,C, while D can occupy any of four positions around it, yielding exactly four orders.

Check your solution

  • The chain order is fixed.
  • D has four possible positions.

8. Count topological orders for independent chains A→B and C→D.

Show hint

Choose the two positions occupied by A and B.

Show worked solution

Choose two of four positions for A and B; their internal order is fixed, as is C before D in the remaining positions. There are binomial(4,2)=6 valid interleavings.

Check your solution

  • Each chain retains its internal order.
  • There are six valid orders.

9. A stalled Kahn remainder contains P,Q,R,S. Give a method to find a cycle witness within it.

Show hint

Follow incoming edges until a vertex repeats.

Show worked solution

Every remaining vertex has a remaining predecessor. Starting at any one, repeatedly follow an incoming edge; finiteness guarantees a repeated vertex. Reverse the repeated segment to obtain a directed cycle witness.

Check your solution

  • Every selected predecessor remains in the remainder.
  • A repeated vertex identifies a cycle segment.

10. Remove one edge from P→Q, Q→R, R→Q while preserving reachability from P.

Show hint

Keep the forward chain.

Show worked solution

Remove R→Q. The remaining P→Q→R keeps Q and R reachable from P and has the valid order P,Q,R; removing Q→R would lose reachability to R.

Check your solution

  • The removed edge is R→Q.
  • The remaining order is P,Q,R.

11. Why is testing if not order unsafe for a topological function returning [] for an empty graph and None for a cycle?

Show hint

Both values are false in Python truth testing.

Show worked solution

The condition treats a valid empty order and the cycle sentinel as the same failure. Test order is None to detect a cycle, and accept [] as the complete order of the empty graph.

Check your solution

  • None denotes the cycle result.
  • The empty list is a valid empty order.

12. A program counts duplicate P→Q edges twice but decrements Q only once. Diagnose and repair it.

Show hint

Use the same multiplicity policy in both phases.

Show worked solution

Q incorrectly retains one incoming count after P is removed and can remain blocked. Decrement once for every stored occurrence, or deduplicate before both the indegree count and removal scan.

Check your solution

  • The erroneous remaining count is one.
  • Consistent counting lets Q reach zero.

13. A graph has isolated P and a self-loop Q→Q. What does the baseline return after P is processed?

Show hint

Compare the processed count with all keys.

Show worked solution

P starts ready and can be emitted, but Q retains its self-loop indegree. The queue then empties with only one of two vertices processed, so the baseline returns None rather than [P].

Check your solution

  • The processed prefix is [P].
  • The final result is None.

14. Count valid orders for P→Q with independent vertex R.

Show hint

P must precede Q but R can be interleaved.

Show worked solution

The valid orders are P,Q,R; P,R,Q; and R,P,Q. The other three permutations put Q before P and violate the edge, so there are exactly three valid orders.

Check your solution

  • There are three valid orders.
  • P precedes Q in each one.

15. Edges A→B and B→C have weights -100 and 5. Does a topological order minimize their weights?

Show hint

Precedence and weighted optimization are different contracts.

Show worked solution

The only chain order is A,B,C because each source must precede its destination. The weights do not affect this topological validity; optimizing a weighted objective requires an additional algorithm and definition.

Check your solution

  • The order is A,B,C.
  • Topological ordering alone does not optimize weights.

16. Compare FIFO and lexicographic ready selection when B and A are initially ready in that insertion order.

Show hint

Both select only zero-indegree vertices.

Show worked solution

FIFO selects B first, while a min-priority queue selects A first. Both are valid if no edge constrains the two; the heap requires comparable keys and adds its own operation costs.

Check your solution

  • FIFO first selects B.
  • Lexicographic selection first chooses A.

17. A DAG has six vertices and eight stored edges. Count edge visits in the two main stages.

Show hint

Count construction and removal separately.

Show worked solution

Indegree construction examines eight edge occurrences. A complete removal pass examines those eight again while decrementing counts, for sixteen visits to edge occurrences across the two stages.

Check your solution

  • Construction scans eight edges.
  • Removal scans eight more edges.

18. Kahn emits [P] then stalls on Q↔R. Explain why [P] is not a complete schedule.

Show hint

Compare emitted count to represented vertices.

Show worked solution

The prefix contains only P, while Q and R remain mutually blocked. It may satisfy constraints among emitted vertices but omits two represented tasks, so the baseline returns None for the complete-order request.

Check your solution

  • The prefix has one vertex.
  • The complete graph has three vertices.

19. Design a brute-force oracle for topological orders on four vertices.

Show hint

Enumerate permutations and test every edge.

Show worked solution

Enumerate all 4!=24 vertex permutations, retain those where every edge points from an earlier to a later position, and compare a candidate result with that set. An empty set indicates no complete order for this finite graph.

Check your solution

  • There are 24 candidate permutations.
  • Each retained permutation satisfies every edge.

20. Design a policy when dependency edges change during ordering.

Show hint

Bind the result to a stable graph version.

Show worked solution

Compute against an immutable snapshot with a version identifier. If the graph changes before the result is used, discard or revalidate the order against the new version; an old ready decision may violate a new prerequisite.

Check your solution

  • The order records its graph version.
  • A changed version requires recomputation or revalidation.

Key takeaways

  • Define edge direction before ordering dependencies.
  • Verify every edge and detect cycles rather than accepting partial output.
  • Edge direction defines prerequisite precedence.
  • An unprocessed vertex can be downstream of a cycle without belonging to it.
  • Several sequences may satisfy the same dependency graph.

Official references