interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 1 · Algorithms · Lesson 15 of 24

Cycles, topological order and union-find

Directed dependency problems ask whether an order exists (no cycle) and what it is (a topological order), while connectivity that grows edge by edge is the job of union-find. Together these cover prerequisites, build and deployment ordering, deadlock-style cycles and redundant connections.
About 5 hFocus mode

Step 1: Learn the ideas

  • DAGs and topological orders
  • Kahn's algorithm (in-degree queue)
  • DFS finishing order and three-state cycle detection
  • Undirected cycle detection and the parent edge
  • Union-find: find, union, path compression, union by rank or size
  • Amortized analysis and the inverse Ackermann function
  • Kruskal's minimum spanning tree as a union-find application
  • Lexicographically smallest order with a heap
  • Strongly connected components (awareness)

Why it matters

Ordering and grouping questions appear wherever there are dependencies: course prerequisites, package managers and build tools, job schedulers, spreadsheet recalculation, and deadlock detection on a wait-for graph. Interviewers use them to check that you know which questions a directed graph can answer, that you detect cycles without false positives, and that you reach for union-find when connectivity grows edge by edge. In infrastructure work the same reasoning shows up in workflow engines and deployment tools that must apply resources in dependency order.

Core ideas

Topological order. An ordering of vertices in which every edge u -> v places u before v. It exists exactly when the directed graph has no cycle (a DAG), and it is usually not unique.

Kahn's algorithm. Compute in-degrees and enqueue every vertex with in-degree 0. Repeatedly remove a vertex, append it to the output, and decrement the in-degree of its successors, enqueuing those that reach 0. Invariant: every output vertex appears after all of its predecessors. If fewer than V vertices are output, every remaining vertex still has a predecessor among the remaining ones, which forces a cycle. Replacing the queue with a min-heap yields the lexicographically smallest order in O(V log V + E).

DFS order and directed cycles. Run DFS from every unvisited vertex and record each vertex when it finishes. For an edge u -> v in a DAG, v finishes before u, so the reversed finish order is a topological order. Keep three states: unvisited, active (on the current recursion path) and done. Reaching an active vertex is a back edge, which closes a directed cycle. Reaching a done vertex is harmless: in the diamond a -> b, a -> c, b -> d, c -> d, vertex d is reached twice with no cycle. A single visited set cannot distinguish these cases, which is the classic bug.

Undirected cycles. Each undirected edge is seen from both ends, so DFS must skip the edge back to its parent; any other visited neighbor closes a cycle. With parallel edges, skip only the specific edge you arrived on, not every edge to the parent. Applying the directed three-state rule unchanged to an undirected graph reports a false cycle as soon as DFS looks back along the edge it arrived on.

Union-find (disjoint set union). It maintains a partition under union(a, b) and find(x), which returns the representative of x's set. Each set is a tree of parent pointers.

  • Union by rank or size attaches the shorter or smaller tree under the other, keeping height O(log n).
  • Path compression makes every node visited by find point directly to the root.

With both, any sequence of m operations on n elements costs O(m α(n)) in total, where α is the inverse Ackermann function, at most 4 for any input you could store. The bound is amortized: an individual find can still walk a long path, but the compression it performs pays for later operations. Union by rank alone keeps every find O(log n); path compression alone gives logarithmic amortized cost.

Union-find detects cycles in undirected graphs as edges arrive: if both endpoints already share a root, the new edge closes a cycle. That is the redundant-connection pattern and the test Kruskal's algorithm uses to skip edges. Union-find cannot detect directed cycles or answer directed reachability, and it does not support deleting edges.

Common misconceptions

  • "Reaching any visited vertex means a directed cycle." Only a vertex on the current DFS path signals a cycle; reaching a finished vertex is normal in DAGs with shared descendants.
  • "There is one correct topological order." Many orders are usually valid, so check that every edge points forward instead of comparing with one expected list. The order is unique only when consecutive vertices are joined by edges (a Hamiltonian path).
  • "Union by rank alone gives near-constant time." Rank alone gives O(log n); the inverse-Ackermann bound needs both heuristics and is amortized, not per operation.
  • "Union-find can replace DFS for any connectivity question." It handles undirected, growing connectivity. It cannot give paths, answer directed reachability or undo unions without extra machinery.
  • "Kahn's algorithm needs a separate cycle check." The output length is the check.

How to approach it

Name the question first. "Can all tasks be completed?" is cycle detection on a directed graph, "give an order" is a topological sort, and "same group?" or "which edge is redundant?" in an undirected setting suggests union-find. Get edge direction right before anything else: if a requires b first, the edge is b -> a. Prefer Kahn's algorithm when recursion depth could be large; prefer DFS when you must report the cycle itself. Write union-find as a small class whose union returns whether a merge happened, and reuse it. Typical follow-ups, especially at mid and senior level: edges arriving as a stream, returning the actual cycle, or running independent tasks in parallel by processing each Kahn frontier as one batch.

Suggested order

  1. 1Read MIT 6.006 Lecture 10 (Depth-First Search), the topological sort and cycle detection sections, including the claim that reversed finishing order is a topological order.
  2. 2Read Erickson Ch. 6 (Depth-First Search) for the active-vertex view of cycle detection and edge classification; skim strong components.
  3. 3Implement Kahn's algorithm and three-state DFS on the same small graph, add one edge that creates a cycle, and confirm both detect it; then test the diamond graph for false positives.
  4. 4Solve Course Schedule with DFS and Course Schedule II with Kahn's algorithm, then Find Eventual Safe States.
  5. 5Read the algs4 union-find case study (1.5) for the progression from quick-find to weighted quick-union with path compression, then write union-find with both heuristics from memory.
  6. 6Solve Redundant Connection, Number of Provinces (with both DFS and union-find) and Satisfiability of Equality Equations, then Accounts Merge and Min Cost to Connect All Points using Kruskal.
  7. 7For deep level only: read Erickson's lecture notes on Disjoint Sets for the amortized analysis behind the inverse-Ackermann bound.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • MIT 6.006 Introduction to Algorithms (Spring 2020)Start here

    MIT OpenCourseWare

    Section: Lecture 10: Depth-First Search

    Full-DFS, graph connectivity, topological sort by reversed finishing order and cycle detection, with proofs.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Algorithms, 4th Edition booksiteStart here

    Princeton University

    Section: 1.5 Case Study: Union-Find

    Step-by-step development of union-find from quick-find to weighted quick-union with path compression, with code and analysis.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Algorithms (Jeff Erickson) with companion lecture notes

    Jeff Erickson, University of Illinois Urbana-Champaign

    Section: Ch. 6: Depth-First Search

    Rigorous treatment of DFS, topological sorting, cycle detection and strong components.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Competitive Programmer’s Handbook

    CSES

    Section: Ch. 16: Directed graphs

    Concise topological sorting and cycle detection; its Ch. 15 covers the union-find structure used by Kruskal.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

For each directed problem, write the edge direction in words before coding ("b must come before a, so b -> a"). Solve Course Schedule once with DFS and once with Kahn's algorithm. For union-find problems, reuse one class you wrote from memory and extend it with counters (number of components, set sizes) instead of rewriting it each time.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1Why does reaching an already finished vertex during directed DFS not imply a cycle?
  2. Question 2How does Kahn's algorithm reveal a cycle, and which vertices remain unprocessed?
  3. Question 3Why is the reverse of the DFS finishing order a topological order?
  4. Question 4What does each union-find heuristic guarantee on its own, and what do they guarantee together?
  5. Question 5When is union-find better than BFS or DFS for connectivity, and when is it the wrong tool?
  6. Question 6How would you return the lexicographically smallest valid order?

You’re done when you can

  • Implement Kahn's algorithm and three-state DFS cycle detection from memory in under 15 minutes each, tested on a diamond-shaped DAG and on a graph with a cycle.
  • Implement union-find with path compression and union by size in under 10 minutes and explain "amortized inverse Ackermann" in one or two sentences.
  • Solve one unseen dependency-ordering problem and one unseen union-find problem in under 30 minutes each.
  • Explain why undirected cycle detection skips the parent edge while directed detection needs an active state.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Your notes and study time

Log study time