1. Concept library
  2. Data Structures & Algorithms
  3. Module 12: Shortest paths and ordering

Concept

Topological sort

A topological order lists the nodes of a directed acyclic graph so every edge points forward: dependencies before the things that need them. Kahn's algorithm peels off nodes with no remaining incoming edges.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a topological order is and why it needs a DAG
  2. Write Kahn's algorithm with in-degree counts
  3. Spot the partial order returned when the graph has a cycle

In practice

A few lines that show Topological sort doing its job.

Python
from collections import deque

def topo_order(graph, nodes):
    indegree = {n: 0 for n in nodes}
    for u in nodes:
        for v in graph[u]:
            indegree[v] += 1
    queue = deque(n for n in nodes if indegree[n] == 0)
    order = []
    while queue:
        n = queue.popleft(); order.append(n)
        for v in graph[n]:
            indegree[v] -= 1
            if indegree[v] == 0: queue.append(v)
    return order if len(order) == len(nodes) else None   # None: a cycle

The common mistake

Watch for

Returning the partial order when the graph has a cycle. If the result has fewer nodes than the graph, there is a cycle, and the caller should be told rather than handed an incomplete list.

What to know first

Your roadmap puts these before Topological sort, unless you already know them.

How it stays learned

Once a session shows you understand Topological sort, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Dijkstra's algorithm
Next in the moduleUnion-find →