PrepStack · Markdown HTML

Topological sort / indegree elimination

Traversal and connectivity · HTML

Formal shape

Maintain remaining indegree indeg[v]. Output any zero-indegree vertex and delete its outgoing edges. If fewer than V vertices are output, the remainder contains a cycle.

Recognition signals

False friends

SignalWhy it is different
Undirected connectivityUndirected edges have no prerequisite direction; indegree elimination is not connectivity.
Profit-aware schedulingTopology supplies feasibility only; optimizing value still needs a heap, greedy proof, or DP.

Core invariant

Every frontier vertex has zero indegree in the remaining graph; outputting u changes only the indegrees of u's direct successors.

State, transition, and processing order

ItemDefinition
StateIndegree map, outgoing adjacency, zero-indegree frontier, and processed count or order.
TransitionRemove and output u; for each u→v decrement indeg[v], adding v exactly when it reaches zero.
Frontier / orderAll currently executable vertices; a queue yields any order, while a min-heap can yield the lexicographically smallest one.

Python skeleton

from collections import deque

def topo_order(nodes, edges):
    graph = {u: [] for u in nodes}
    indeg = {u: 0 for u in nodes}
    for u, v in edges:
        graph[u].append(v)
        indeg[v] += 1
    q = deque(u for u in nodes if indeg[u] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in graph[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == len(nodes) else None

Correctness sketch

  1. A vertex is output only with zero remaining indegree, so every prerequisite still represented in the graph is already satisfied.
  2. Every nonempty DAG has a zero-indegree vertex, so elimination cannot stall on an acyclic remainder.
  3. If elimination stalls with vertices left, following predecessors indefinitely in a finite graph repeats a vertex and forms a directed cycle.

Complexity

TimeSpaceParameters
O(V+E)O(V+E)V is the task count and E the dependency count; each edge is built and removed once.

Edge cases

Error patterns

PatternWhy it fails / fix
Reversing edge directionFor prereq→task, increment the task's indegree.
Dropping isolated tasksInferring nodes solely from edges loses tasks with no dependencies.
Wrong cycle testKahn's criterion is processed==V, not a plain visited set.

Selection and exclusion rules

RelationTemplateBoundary

Original micro-example

PartDetail
Resultgrind, clean, brew, serve is valid but not unique.
Setupbrew requires grind, serve requires brew, and clean has no prerequisite.
Tracegrind and clean start available; completing grind releases brew, which later releases serve.

Recall prompts

My notes