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.
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.
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
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.