7 routes42 sections324 units

Unit 3.4 · about 4 h

107 / 324

Topological ordering and strongly connected components

Dependency order is the scheduling primitive: builds, courses, task graphs. The same DFS skeleton that orders a DAG also carves directed graphs into strongly connected components.

  • derive
  • implement

You can now

  • Implement Kahn's algorithm and DFS post-order topological sort, each with its cycle witness, and derive the \(\Theta(V + E)\) bound.
  • Prove post-order-then-reverse is a topological order from the finish-time invariant.
  • Implement Kosaraju's strongly connected components and explain the reverse-graph second pass.

Covers

  • Topological ordering and dependency cycles
  • Strongly connected components

Study, in this order

3 steps

  1. Topological sort: Kahn's algorithm
    DSA Handbook - graphs

    What Kahn's actually does; The algorithm (LC 207); Worked example on the 6-course catalog; Reverse-graph Kahn for safe nodes (LC 802)

  2. Topological sort: DFS post-order reverse
    DSA Handbook - graphs

    Why two colors are not enough; The algorithm; Walking the canonical DAG; Why post-order, then reverse, is correct; Picking between Kahn and DFS

  3. Topological sort and strong components
    Algorithms - graph chapters

    Section 6.3 Topological Sort with Implicit Topological Sort; Sections 6.5 Strong Connectivity and 6.6 Strong Components in Linear Time, Kosaraju and Sharir's algorithm (printed pp. 232-234 and 237-244; Tarjan's algorithm is optional)

Focus on

  • Pin the edge convention in a comment: [a,b] means \(b\) is the prerequisite, so the edge is \(b \to a\). Inverting it turns DAGs into cycles.
  • Kahn detects the cycle only at termination: emitted count equal to \(V\) means DAG, fewer means the leftovers sit on cycles. No early return inside the loop.
  • DFS emits each vertex after all successors finish, so finish times decrease along every edge; reversing puts producers first. A GRAY successor aborts with a cycle.
  • Kosaraju finishes SCCs in topological order on the first pass, then walks the reversed graph from the latest-finishing component, which cannot escape its own SCC.

Reproduce closed-book

From a blank file with the course Python (3.13.14), run Kahn on \(n = 6\) with [[1,0],[2,0],[3,1],[3,2],[4,2],[5,3],[5,4]] and emit a valid order such as [0,1,2,3,4,5] (check every \(b\) precedes its \(a\)); on [[1,0],[0,1]] emit 0 of 2 and report a cycle. Then run Kosaraju on [(0,1),(1,2),(2,0),(2,3),(3,4)] and report components [0,0,0,1,2].

Traps

  • Counting indegrees from one edge collection and decrementing from another, such as a deduplicated set against the raw list with duplicate prerequisites: counts go negative or never reach zero. Count and decrement from the same list, and enqueue exactly when a count reaches 0.
  • Returning the post-order list unreversed: it holds consumers before producers, the exact opposite of the graded order.
  • Running DFS from vertex 0 only: cycles in other weakly connected components are missed. The outer white-check loop is mandatory, as is the GRAY-to-BLACK flip on exit.

Practice

LeetCode 210: Course Schedule II

Examples 1 to 3 (2 courses [[1,0]]; 4 courses [[1,0],[2,0],[3,1],[3,2]]; single course with no prerequisites)

Attempt cold per the AlgoMaster pool note, in either Kahn or DFS framing, then implement the other framing and compare orders. After-attempt reference is DSA Handbook 8.4 (Kahn) and 8.5 (post-order).

LeetCode 802: Find Eventual Safe States

The two listed examples (7-node graph with two safe terminals; 5-node graph)

Reverse-graph Kahn from terminal vertices, or three-color DFS; state which witness you report. After-attempt reference is the reverse-graph section of DSA Handbook 8.4.

Self-test

  1. Prove post-order-then-reverse is a topological order.

  2. Prove leftover vertices after Kahn imply a cycle.

  3. Why does Kosaraju's second pass stay inside one SCC?

  4. Kahn and DFS report different valid orders on the same DAG. Is one wrong?

Completion criterion

Stop when

Your blank-file script prints a valid 6-course order, the 0-of-2 cycle verdict and the [0,0,0,1,2] component labels, and you can defend the Kahn-versus-DFS choice on operational grounds (iteration and lex order versus post-order computation).

Mark passed, then open 3.5 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • DSA Handbook - graphs
    Handbook Academyprimarycourse
    Study all of Part 8 in order. For each algorithm, write the representation, invariant, forbidden input assumptions and independently checkable output before reading the implementation.
  • Algorithms - graph chapters
    Jeff Ericksonrequiredtheory
    Use the basic graph, depth-first search, minimum spanning tree, shortest path and flow chapters, and lecture note 11 Disjoint Sets for union-find, for correctness proofs and counterexamples to tempting wrong algorithms.

Also in this section

  • AlgoMaster DSA - graph slice
    AlgoMasterrequiredpractice
    Attempt Number of Islands, Course Schedule II and Network Delay Time cold. They cover traversal, dependency modeling and weighted shortest paths; add one narrative problem only if graph modeling remains weak.
  • Hypothesis - generated graph tests
    Hypothesissupportpractice
    Generate small sparse, dense, disconnected, cyclic, parallel-edge and weighted graphs. Compare optimized results with exhaustive or deliberately simple references and retain shrunk failures.
  • NeetCode - unseen graph problems
    NeetCodeoptionalassessment
    Use two unseen story problems without graph tags. Grade the model, assumptions, certificate and tests as well as the final answer.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels