Lesson 23 of 40Graphs in depth
Cycles, Ordering and Bipartite Graphs
Detect cycles with three-colour DFS, order DAGs by reverse post-order or layers, find longest paths, and two-colour graphs.
Every build tool, package manager and job scheduler you will use at work has a graph inside it. Bazel, Gradle, npm, Terraform and Airflow all need the same three answers: is there a circular dependency, and if so which nodes are in it; what order can things run in; and how many rounds does it take if independent jobs run in parallel. A good error message ("cycle: auth → crypto → config → auth") is worth far more than "cycle detected".
In Graphs you met Kahn's algorithm, which gives a topological order and tells you a cycle exists when nodes are left over. This lesson goes further: finding the actual cycle, the DFS route to an ordering, layered ordering, longest paths, and two-colouring. These are the techniques behind Course Schedule II, Alien Dictionary, Parallel Courses, Is Graph Bipartite, Clone Graph and Reconstruct Itinerary.
Why a visited set is not enough in a directed graph
In an undirected graph, meeting an already-visited node (other than the one you came from) means a cycle. In a directed graph that rule gives false alarms. Take app → auth → crypto and app → db → crypto. DFS reaches crypto through auth, finishes it, then reaches it again through db. That is a diamond, not a cycle. Nothing loops back.
The fix is to remember where each node is in its life, using three colours:
- White: not seen yet.
- Grey: entered, but DFS has not finished its descendants. Grey nodes are exactly the nodes on the current DFS path (the recursion stack).
- Black: finished. Every node reachable from it has been explored.
An edge to a grey node points back up the current path, so it closes a loop: a back edge, and a cycle. An edge to a black node is harmless; that node and everything below it is already fully explored, and none of it leads back to the current path, or DFS would have found the cycle then.
Enter A. It turns grey: it is on the current path.
To report the cycle, keep a parent map as you go deeper. When you find a back edge u → v, walk parents from u until you reach v. The version below uses an explicit stack of (node, iterator) pairs, so a dependency chain of 50,000 packages will not hit Python's 1,000-frame recursion limit.
Press Run (⌘ Enter) to see what happens.Kahn's algorithm also detects cycles (nodes left with in-degree above zero), but the leftovers include nodes that merely sit downstream of a cycle, not just the cycle itself. When you need to name the culprits, use the three colours.
Undirected cycles: skip the edge you arrived by
Undirected graphs need only two states, seen and unseen, with one catch. Every edge appears in both directions, so from v you will always see the node you just came from. Skip it. Any other seen neighbour closes a cycle.
The tidy way is to skip the edge id you arrived by, not the parent node. That handles parallel edges correctly: two separate cables between the same two servers do form a cycle, and "skip the parent" would miss it.
Press Run (⌘ Enter) to see what happens.When edges arrive one at a time and you want the first edge that creates a cycle (Redundant Connection), union-find is simpler; the Union-Find in Depth lesson covers it.
Topological order from DFS: reverse post-order
Here is the second way to order a DAG. Run three-colour DFS and append each node to a list at the moment it turns black. That list is the post-order. Reverse it and you have a topological order.
Why it works: a node turns black only after everything it points to has turned black. So for every edge u → v, v lands in the post-order list before u. Reversed, u comes first. That is exactly the rule a topological order needs. The grey check still runs, so you get cycle detection for free.
Press Run (⌘ Enter) to see what happens.| Kahn's (in-degree queue) | DFS reverse post-order | |
|---|---|---|
| Cost | O(V + E) | O(V + E) |
| Cycle signal | Fewer than V nodes placed | Edge to a grey node |
| Can name the cycle | Not directly | Yes, from the parent chain |
| Gives layers / rounds | Yes, naturally | No |
| Smallest order by label | Swap the queue for a min-heap | Awkward |
Most topological orders are not unique. If a problem says "return any valid order", either works. If it says "the lexicographically smallest", use Kahn's with a heap, which costs O(V log V + E). The heap picks the smallest ready node at each step, and a smaller ready node can never be made invalid by waiting, so greedy is safe here.
Alien Dictionary: building the graph is the hard part
You get words sorted in an unknown alphabet, for example ["wrt", "wrf", "er", "ett", "rftt"], and must return a letter order. The topological sort is the easy half. Interviewers watch how you build the edges:
- Every letter in every word is a node, even letters that never appear in a comparison.
- For each adjacent pair of words, find the first position where they differ. That gives exactly one edge,
w1[i] → w2[i]. Later letters tell you nothing, because the order was already decided at positioni. - If no position differs and the first word is longer (
"abc"before"ab"), the input is impossible. A prefix must come first in any alphabet. Return"". - Topologically sort. If letters are left over, the rules contradict each other: return
"".
Press Run (⌘ Enter) to see what happens.Two subtle bugs to avoid. First, adding the same edge twice inflates the in-degree, so a letter never reaches zero and you wrongly report a contradiction; the duplicate check prevents that. Second, comparing every pair of words instead of adjacent ones is O(n²) and adds nothing, because sorted order is transitive.
Using alien_order above, what does this print?
print(repr(alien_order(["z", "x", "z"])))
Put the Alien Dictionary steps in order.
- Tap the steps below in the right order.
Layers: how many rounds with unlimited parallelism?
Parallel Courses asks: if you can take any number of courses per semester, how many semesters do you need? A CI system asks the same thing about build steps on unlimited runners.
Run Kahn's algorithm level by level, the same snapshot trick you used for BFS by levels in Trees. Every node with in-degree 0 now goes in this round; nodes they unlock go in the next round. The number of rounds equals the number of nodes on the longest path in the DAG. That longest chain is the critical path, and no amount of parallelism can beat it.
When each job has a duration (Parallel Courses III), switch from counting rounds to dynamic programming in topological order: a job can start once its slowest prerequisite finishes, so finish[v] = time[v] + max(finish[u] for each prerequisite u). The answer is the largest finish. Processing in topological order guarantees every finish[u] is final before you read it.
Press Run (⌘ Enter) to see what happens.Longest paths: easy on a DAG, hopeless in general
Longest simple path in a general graph is NP-hard; nobody knows a polynomial algorithm. On a DAG it is O(V + E), because there are no cycles to walk around forever, and topological order lets you process each node after all its predecessors. That contrast is a good thing to mention in an interview.
Often the DAG is hidden. In Longest Increasing Path in a Matrix, draw an edge from each cell to every neighbour with a strictly larger value. A path that strictly increases can never come back to a cell, so the graph is a DAG, and you can memoise "longest path starting here" without any visited set.
Press Run (⌘ Enter) to see what happens.Each cell is solved once and looks at four neighbours: O(rows × cols). The recursion can go as deep as the longest path, so on a 200 × 200 snake-shaped matrix you would switch to the iterative alternative: peel cells in rounds by "number of smaller neighbours", which is Kahn's algorithm on the implicit DAG.
Bipartite graphs: two-colouring
A graph is bipartite if you can split its nodes into two groups so that every edge crosses between the groups. Job applicants and jobs, users and the items they rated, and "put these people on two teams so no two who dislike each other share a team" (Possible Bipartition) are all bipartite questions.
The test is BFS (or DFS) with two colours. Colour the start 0. Every neighbour must get the opposite colour. If you ever find an edge whose two ends already have the same colour, the graph is not bipartite. Underneath, this is a theorem: a graph is bipartite exactly when it has no odd-length cycle. Walking around an odd cycle, the colours must alternate an odd number of times and come back mismatched.
Start at A with colour 0.
Press Run (⌘ Enter) to see what happens.The outer loop over every start node matters. Is Graph Bipartite gives you an adjacency list that can be disconnected, and a solution that only searches from node 0 passes the examples and fails the hidden tests.
Clone Graph: map old to new
Clone Graph asks for a deep copy of a connected undirected graph. The whole trick is one dictionary from each original node to its copy. Create the copy when you discover a node, before you visit it, and the same dictionary doubles as your visited set. Cycles then resolve themselves: when you meet a node again, you link to the copy that already exists instead of creating a second one.
Press Run (⌘ Enter) to see what happens.Reconstruct Itinerary: Eulerian paths with Hierholzer's algorithm
Reconstruct Itinerary gives you airline tickets and asks for a route from JFK that uses every ticket exactly once, picking the lexicographically smallest route when several work. Using every edge once is an Eulerian path, not a topological sort.
The tempting greedy (always fly to the smallest next airport) can get stuck. With tickets JFK→KUL, JFK→NRT, NRT→JFK, greedy flies to KUL first and strands the other two tickets.
Hierholzer's algorithm fixes it by appending an airport to the route only when it has no tickets left (post-order), then reversing. A dead end like KUL gets appended first, so it ends up last in the final route, after the loop through NRT has been spliced in. Each ticket is used once: O(E log E) for the sort.
Press Run (⌘ Enter) to see what happens.An Eulerian path exists in a directed graph only if every node has equal in- and out-degree, except possibly one start (one more out) and one end (one more in), and all edges are connected. Interviewers rarely ask for the proof; recognising "use every edge once" is the point.
Match each problem to the technique that fits it best.
- back edge
- In DFS on a directed graph, an edge to a node still on the current path (grey). Its presence is exactly what makes the graph cyclic.
- three-colour DFS
- White = unseen, grey = on the current path, black = finished. Grey hits are cycles; black hits are harmless.
- reverse post-order
- List nodes as they finish in DFS, then reverse. For a DAG, this is a topological order.
- critical path
- The longest chain in a dependency DAG. It sets the minimum number of rounds, or the minimum total time, even with unlimited parallelism.
- bipartite graph
- Nodes split into two groups with every edge crossing between them. True exactly when the graph has no odd cycle.
- Eulerian path
- A walk that uses every edge exactly once. Found with Hierholzer's algorithm by appending nodes in post-order.