Skip to contentKEEP THE CRAFTTHE SANCTUARY

Topological Sort

Order directed prerequisites so every edge points forward. Compare reversed DFS postorder with zero-indegree removal, detect cycles, and distinguish any valid ordering from the lexicographically smallest one.

2 practice exercises5 interview problems

Recognize it when Tasks can begin only after all incoming prerequisite edges are resolved.

Checking your account…

Topological Sort Code Labs

Order Every Edge Forward

A topological order lists every vertex of a directed acyclic graph so each edge source appears before its target. It is a precedence contract, not merely a traversal order.

Choose DFS Postorder or Indegrees

With prerequisite-to-dependent edges, DFS appends a node after its outgoing descendants (its dependents), then reverses postorder to place prerequisites first. Kahn’s algorithm repeatedly removes zero-indegree nodes. Both take O(V + E), but expose different cycle evidence and ordering controls.

Check a Candidate Topological Order

Reference
def is_topological_order(node_count,edges,order):
    if len(order)!=node_count or set(order)!=set(range(node_count)):return False
    position={node:index for index,node in enumerate(order)}
    return all(source in position and target in position and position[source]<position[target] for source,target in edges)
Practice

Implement is_topological_order(node_count,edges,order). Return whether order contains every node once and places each directed edge forward. Require a nonnegative integer node_count and edge endpoints in 0..node_count-1.

Public tests

  • Require every edge to point forward

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Check a Candidate Topological Order

def is_topological_order(node_count,edges,order):
    if len(order)!=node_count or set(order)!=set(range(node_count)):return False
    position={node:index for index,node in enumerate(order)}
    return all(source in position and target in position and position[source]<position[target] for source,target in edges)

Detect When No Order Exists

A directed cycle makes every cycle node depend on another cycle node. DFS detects an edge to the active path; Kahn detects that fewer than V nodes were processed.

Build a Deterministic Topological Order

Reference
import heapq

def topological_order(node_count,edges):
    adjacency=[[] for _ in range(node_count)];indegree=[0]*node_count
    for source,target in edges:adjacency[source].append(target);indegree[target]+=1
    ready=[node for node in range(node_count) if indegree[node]==0];heapq.heapify(ready);order=[]
    while ready:
        node=heapq.heappop(ready);order.append(node)
        for neighbor in adjacency[node]:
            indegree[neighbor]-=1
            if indegree[neighbor]==0:heapq.heappush(ready,neighbor)
    return order if len(order)==node_count else []
Practice

Implement topological_order(node_count,edges). Return the lexicographically smallest valid order, or [] for a cycle. Require a nonnegative integer node_count and edge endpoints in 0..node_count-1.

Public tests

  • Return deterministic DAG order or no order

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build a Deterministic Topological Order

import heapq

def topological_order(node_count,edges):
    adjacency=[[] for _ in range(node_count)];indegree=[0]*node_count
    for source,target in edges:adjacency[source].append(target);indegree[target]+=1
    ready=[node for node in range(node_count) if indegree[node]==0];heapq.heapify(ready);order=[]
    while ready:
        node=heapq.heappop(ready);order.append(node)
        for neighbor in adjacency[node]:
            indegree[neighbor]-=1
            if indegree[neighbor]==0:heapq.heappush(ready,neighbor)
    return order if len(order)==node_count else []

Let a Newly Available Smaller Node Overtake

Run the existing heap-based order Lab on one edge and two isolated nodes. Predict the newly released node before considering a FIFO alternative; its position reveals the stronger lexicographic contract.

Step Executed statement State Why
Build incoming counts indegree[target]+=1 indegree=[0, 1, 0, 0] Only node 1 has an unresolved prerequisite.
Seed candidates ready=[node for node in range(node_count) if indegree[node]==0];heapq.heapify(ready) ready=[0, 2, 3] Include isolated nodes because the order must contain every vertex.
Resolve node 1 node=heapq.heappop(ready);order.append(node); indegree[neighbor]-=1; heapq.heappush(ready,neighbor) after removing 0: order=[0], ready minimum=1 The newly ready 1 competes immediately with 2 and 3.
Emit remaining nodes node=heapq.heappop(ready);order.append(node) order=[0, 1, 2, 3] after remaining iterations Smallest-ready choices give the lexicographically smallest valid sequence.
Cycle call return order if len(order)==node_count else [] only isolated 0 emitted; result=[] The cycle between 1 and 2 prevents a complete order despite a nonempty partial prefix.
Print Output
print(topological_order(4, [[0, 1]])) [0, 1, 2, 3]
print(topological_order(3, [[1, 2], [2, 1]])) []

The candidate-check Lab focuses on the edge-forward definition, while the order Lab constructs an answer. A topological order is generally not unique, and a cycle witness is a separate output contract.

Handle Multiple Valid Orders

A DAG may have many valid orders. Use a heap when the contract requests lexicographically smallest output; otherwise any deterministic queue or traversal order is acceptable.

Explain It in an Interview

Say: “A valid order places every directed edge forward. I remove currently dependency-free nodes and decrement exactly their outgoing edges; processing fewer than V nodes proves a cycle.” Mention isolated nodes and duplicate-edge policy.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Topological sort (Kahn's algorithm)

Take the zero in-degree nodes, cut their edges, repeat; leftovers mean a cycle.

Tasks have prerequisites and you need a valid order, or must detect a cycle.

Trigger words

  • prerequisites
  • course schedule
  • build order
  • dependencies
  • valid ordering
  • alien dictionary
  • cycle in directed graph
from collections import deque

def course_order(num_courses, prerequisites):
    graph = [[] for _ in range(num_courses)]
    indegree = [0] * num_courses
    for course, before in prerequisites:     # `before` must be taken first
        graph[before].append(course)
        indegree[course] += 1

    queue = deque([c for c in range(num_courses) if indegree[c] == 0])
    order = []
    while queue:
        course = queue.popleft()
        order.append(course)
        for nxt in graph[course]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)

    if len(order) < num_courses:             # some courses never freed: a cycle
        return []
    return order

Spot it when

  • 'Course schedule', 'prerequisites', 'build order'.
  • 'Alien dictionary' (order from comparisons).

Remember

  • indegree[x] counts unfinished prerequisites of x.
  • If the order is shorter than the number of nodes, there is a cycle.

How problems bend it

  • Can you finish all courses?: Return len(order) == num_courses.
  • Alien dictionary: Build edges from the first differing letter of each adjacent word pair.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Topological Sort proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
DFS/FIFO topological orderingO(V + E)O(V + E)Adjacency-list graph; no priority sorting.
Lexicographically smallest heap orderingO(E + V log V)O(E + V log V)The current order Lab uses a min heap.

Space

O(V + E) built adjacency plus indegree/frontier or DFS colors/frames.

Assumptions

  • Duplicate edges must be counted and removed consistently.
  • A cycle can leave otherwise valid isolated-node output; processed count must still equal V.

Invariants Worth Saying Aloud

  1. Every emitted node has no unmet incoming dependency from unprocessed nodes.
  2. Every directed edge goes from an earlier emitted source to a later emitted target.

When To Use Or Avoid Topological Sort

Use It When

  • Use topological order for DAG scheduling or a dependency-ordered dynamic program.
  • Choose a min heap when the smallest currently available node is part of the output contract.

Choose Another Tool When

  • A directed cycle prevents a complete order; detect it rather than returning a partial prefix.
  • An undirected traversal order is not a directed dependency order.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Counting outgoing edges as prerequisites

For edge 0 -> 1, indegree belongs to node 1, not 0. Reversing that update offers the dependent first.

Prevent it: Increment the target indegree for each prerequisite edge.

Avoid

indegree[source] += 1

Use instead

indegree[target] += 1

Accepting a partial prefix as a complete order

An isolated node can be emitted even while two other nodes form a cycle. A nonempty result is not evidence of full feasibility.

Prevent it: Require the emitted count to equal all vertices.

Avoid

complete = bool(order)

Use instead

complete = len(order) == node_count

Using FIFO for a smallest-ready contract

A newly ready node 1 must precede already queued 2 and 3 under lexicographic ordering. FIFO appends it behind them.

Prevent it: Use a min heap only when this stronger ordering is required.

Avoid

ready.append(new)
node = ready.pop(0)

Use instead

heapq.heappush(ready, new)
node = heapq.heappop(ready)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.