Skip to content

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.

20 min read0/6 questions

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.

Three-colour DFS (sky = grey, on the path; green = black, finished)
AgreyBCD

currentwaitingdone

Enter A. It turns grey: it is on the current path.

1/6

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.

Python
WHITE, GREY, BLACK = 0, 1, 2DONE = object() # sentinel: the iterator has no more neighbours def find_cycle(graph): """Return one directed cycle as [v, ..., v], or None if the graph is a DAG.""" colour = {u: WHITE for u in graph} parent = {} for start in graph: if colour[start] != WHITE: continue colour[start] = GREY stack = [(start, iter(graph[start]))] while stack: u, neighbours = stack[-1] v = next(neighbours, DONE) if v is DONE: colour[u] = BLACK # all of u's descendants are explored stack.pop() elif colour[v] == WHITE: colour[v] = GREY parent[v] = u stack.append((v, iter(graph[v]))) elif colour[v] == GREY: # back edge: v is on the current path path = [u] while path[-1] != v: path.append(parent[path[-1]]) return path[::-1] + [v] # BLACK: already finished, cannot lead back to the path return None def naive_has_cycle(graph): """The WRONG version: treats any revisit as a cycle.""" seen = set() def dfs(u): if u in seen: return True seen.add(u) return any(dfs(v) for v in graph[u]) return any(dfs(u) for u in graph if u not in seen) diamond = {"app": ["auth", "db"], "auth": ["crypto"], "db": ["crypto"], "crypto": []}assert find_cycle(diamond) is Noneassert naive_has_cycle(diamond) is True # false alarm looped = {"app": ["auth"], "auth": ["crypto"], "crypto": ["config"], "config": ["auth"]}assert find_cycle(looped) == ["auth", "crypto", "config", "auth"]assert find_cycle({"x": ["x"]}) == ["x", "x"] # a self-loop is a cycle print("cycle:", " -> ".join(find_cycle(looped)))
Output
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.

Quick check
During DFS on a directed graph you follow an edge u → v and find v is black. What does that tell you?
Need a nudge? A hint rules out a wrong answer.

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.

Python
def has_undirected_cycle(n, edges): graph = [[] for _ in range(n)] for eid, (a, b) in enumerate(edges): graph[a].append((b, eid)) graph[b].append((a, eid)) seen = [False] * n for s in range(n): # every component, not just node 0 if seen[s]: continue seen[s] = True stack = [(s, -1)] # (node, id of the edge we arrived by) while stack: u, via = stack.pop() for v, eid in graph[u]: if eid == via: continue if seen[v]: return True seen[v] = True stack.append((v, eid)) return False def valid_tree(n, edges): # A tree on n nodes has exactly n - 1 edges and no cycle (which forces connected). return len(edges) == n - 1 and not has_undirected_cycle(n, edges) assert not has_undirected_cycle(4, [(0, 1), (1, 2), (2, 3)])assert has_undirected_cycle(3, [(0, 1), (1, 2), (2, 0)])assert has_undirected_cycle(2, [(0, 1), (0, 1)]) # parallel edgesassert has_undirected_cycle(5, [(0, 1), (2, 3), (3, 4), (4, 2)]) # cycle in a later componentassert valid_tree(5, [(0, 1), (0, 2), (0, 3), (1, 4)])assert not valid_tree(5, [(0, 1), (1, 2), (2, 3), (1, 3), (1, 4)])assert not valid_tree(4, [(0, 1), (1, 2), (2, 0)]) # n - 1 edges, but a cycle leaves node 3 outprint("undirected checks pass")
Output
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.

Python
import heapq def topo_dfs(n, edges): """edges are (before, after). Returns an order, or [] if there is a cycle.""" graph = [[] for _ in range(n)] for a, b in edges: graph[a].append(b) colour = [0] * n post = [] for s in range(n): if colour[s]: continue colour[s] = 1 stack = [(s, iter(graph[s]))] while stack: u, it = stack[-1] v = next(it, -1) if v == -1: colour[u] = 2 post.append(u) # finished: all of u's successors are in post stack.pop() elif colour[v] == 0: colour[v] = 1 stack.append((v, iter(graph[v]))) elif colour[v] == 1: return [] # back edge return post[::-1] def smallest_topo(n, edges): """Kahn's with a min-heap: the lexicographically smallest valid order.""" graph = [[] for _ in range(n)] indeg = [0] * n for a, b in edges: graph[a].append(b) indeg[b] += 1 heap = [i for i in range(n) if indeg[i] == 0] heapq.heapify(heap) order = [] while heap: u = heapq.heappop(heap) order.append(u) for v in graph[u]: indeg[v] -= 1 if indeg[v] == 0: heapq.heappush(heap, v) return order if len(order) == n else [] def respects(order, edges): pos = {u: i for i, u in enumerate(order)} return all(pos[a] < pos[b] for a, b in edges) edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]order = topo_dfs(6, edges)assert respects(order, edges) and len(order) == 6assert smallest_topo(6, edges) == [4, 5, 0, 2, 3, 1]assert topo_dfs(3, [(0, 1), (1, 2), (2, 0)]) == [] # Course Schedule II gives [course, prereq], so the edge is prereq -> course.prereqs = [[1, 0], [2, 0], [3, 1], [3, 2]]course_order = topo_dfs(4, [(p, c) for c, p in prereqs])assert respects(course_order, [(p, c) for c, p in prereqs])print("DFS order:", order, " smallest:", smallest_topo(6, edges))
Output
Press Run (⌘ Enter) to see what happens.
Kahn's (in-degree queue)DFS reverse post-order
CostO(V + E)O(V + E)
Cycle signalFewer than V nodes placedEdge to a grey node
Can name the cycleNot directlyYes, from the parent chain
Gives layers / roundsYes, naturallyNo
Smallest order by labelSwap the queue for a min-heapAwkward

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:

  1. Every letter in every word is a node, even letters that never appear in a comparison.
  2. 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 position i.
  3. 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 "".
  4. Topologically sort. If letters are left over, the rules contradict each other: return "".
Python
from collections import deque def alien_order(words): graph = {c: [] for w in words for c in w} indeg = {c: 0 for c in graph} for w1, w2 in zip(words, words[1:]): for a, b in zip(w1, w2): if a != b: if b not in graph[a]: # do not count a duplicate edge twice graph[a].append(b) indeg[b] += 1 break # only the FIRST difference matters else: if len(w1) > len(w2): return "" # "abc" before "ab" is impossible queue = deque(sorted(c for c in graph if indeg[c] == 0)) order = [] while queue: c = queue.popleft() order.append(c) for nxt in graph[c]: indeg[nxt] -= 1 if indeg[nxt] == 0: queue.append(nxt) return "".join(order) if len(order) == len(graph) else "" assert alien_order(["wrt", "wrf", "er", "ett", "rftt"]) == "wertf"assert alien_order(["z", "x"]) == "zx"assert alien_order(["abc", "ab"]) == ""assert alien_order(["ab", "abc"]) in ("abc", "acb", "bac", "bca", "cab", "cba")assert alien_order(["z", "z"]) == "z"print(alien_order(["wrt", "wrf", "er", "ett", "rftt"]))
Output
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.

Predict the outputPython

Using alien_order above, what does this print?

print(repr(alien_order(["z", "x", "z"])))
Need a nudge? Hints walk you through it.
Put it in order5 steps

Put the Alien Dictionary steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Python
def min_semesters(n, relations): """Courses 1..n, relations are [before, after]. -1 if impossible.""" graph = [[] for _ in range(n + 1)] indeg = [0] * (n + 1) for a, b in relations: graph[a].append(b) indeg[b] += 1 layer = [c for c in range(1, n + 1) if indeg[c] == 0] semesters = taken = 0 while layer: semesters += 1 taken += len(layer) nxt = [] for u in layer: for v in graph[u]: indeg[v] -= 1 if indeg[v] == 0: nxt.append(v) layer = nxt return semesters if taken == n else -1 def min_total_time(n, relations, time): """Parallel Courses III: time[i] is the length of course i + 1.""" graph = [[] for _ in range(n + 1)] indeg = [0] * (n + 1) for a, b in relations: graph[a].append(b) indeg[b] += 1 start = [0] * (n + 1) # earliest moment each course can begin ready = [c for c in range(1, n + 1) if indeg[c] == 0] best = 0 while ready: u = ready.pop() done = start[u] + time[u - 1] best = max(best, done) for v in graph[u]: start[v] = max(start[v], done) indeg[v] -= 1 if indeg[v] == 0: ready.append(v) return best assert min_semesters(3, [[1, 3], [2, 3]]) == 2assert min_semesters(3, [[1, 2], [2, 3], [3, 1]]) == -1assert min_semesters(4, [[1, 2], [2, 3], [3, 4]]) == 4assert min_total_time(3, [[1, 3], [2, 3]], [3, 2, 5]) == 8assert min_total_time(5, [[1, 5], [2, 5], [3, 5], [3, 4], [4, 5]], [1, 2, 3, 4, 5]) == 12print("semesters:", min_semesters(3, [[1, 3], [2, 3]]))
Output
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.

Python
from functools import cache def longest_increasing_path(matrix): rows, cols = len(matrix), len(matrix[0]) @cache def best(r, c): # longest increasing path starting at (r, c) length = 1 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]: length = max(length, 1 + best(nr, nc)) return length return max(best(r, c) for r in range(rows) for c in range(cols)) assert longest_increasing_path([[9, 9, 4], [6, 6, 8], [2, 1, 1]]) == 4 # 1, 2, 6, 9assert longest_increasing_path([[3, 4, 5], [3, 2, 6], [2, 2, 1]]) == 4 # 3, 4, 5, 6assert longest_increasing_path([[7]]) == 1print(longest_increasing_path([[9, 9, 4], [6, 6, 8], [2, 1, 1]]))
Output
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.

Quick check
Why can Longest Increasing Path in a Matrix memoise without a visited set, when DFS on a general grid needs one?
Need a nudge? A hint rules out a wrong answer.

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.

Two-colouring finds an odd cycle
A0BCDE

currentwaitingdone

Start at A with colour 0.

1/5
Python
from collections import deque def two_colour(n, edges): """Return a colour list (0/1 per node), or None if not bipartite.""" graph = [[] for _ in range(n)] for a, b in edges: graph[a].append(b) graph[b].append(a) colour = [-1] * n for s in range(n): # disconnected graphs: try every start if colour[s] != -1: continue colour[s] = 0 queue = deque([s]) while queue: u = queue.popleft() for v in graph[u]: if colour[v] == -1: colour[v] = 1 - colour[u] queue.append(v) elif colour[v] == colour[u]: return None return colour def possible_bipartition(n, dislikes): """People are 1..n. Shift to 0-based and two-colour.""" return two_colour(n, [(a - 1, b - 1) for a, b in dislikes]) is not None square = [(0, 1), (1, 2), (2, 3), (3, 0)]teams = two_colour(4, square)assert teams is not None and all(teams[a] != teams[b] for a, b in square)assert two_colour(3, [(0, 1), (1, 2), (2, 0)]) is Noneassert two_colour(5, [(0, 1), (2, 3), (3, 4), (4, 2)]) is None # the odd cycle is in part twoassert possible_bipartition(4, [[1, 2], [1, 3], [2, 4]])assert not possible_bipartition(3, [[1, 2], [1, 3], [2, 3]])print("teams for the square:", teams)
Output
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.

Python
from collections import deque class Node: def __init__(self, val, neighbors=None): self.val = val self.neighbors = neighbors if neighbors is not None else [] def clone_graph(node): if node is None: return None copies = {node: Node(node.val)} queue = deque([node]) while queue: u = queue.popleft() for v in u.neighbors: if v not in copies: copies[v] = Node(v.val) queue.append(v) copies[u].neighbors.append(copies[v]) return copies[node] # Build the square 1 - 2 - 3 - 4 - 1.n1, n2, n3, n4 = Node(1), Node(2), Node(3), Node(4)n1.neighbors, n2.neighbors = [n2, n4], [n1, n3]n3.neighbors, n4.neighbors = [n2, n4], [n3, n1] c1 = clone_graph(n1)assert c1 is not n1 and c1.val == 1assert [x.val for x in c1.neighbors] == [2, 4]c2 = c1.neighbors[0]assert c2 is not n2 and c2.neighbors[0] is c1 # the cycle points at the copyassert c2.neighbors[1].neighbors[1] is c1.neighbors[1] # node 4 was copied onceprint("cloned values:", [x.val for x in c1.neighbors])
Output
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.

Python
from collections import defaultdict def find_itinerary(tickets): graph = defaultdict(list) for a, b in sorted(tickets, reverse=True): graph[a].append(b) # reversed so pop() gives the smallest route, stack = [], ["JFK"] while stack: while graph[stack[-1]]: stack.append(graph[stack[-1]].pop()) route.append(stack.pop()) # no tickets left here: post-order return route[::-1] assert find_itinerary([["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]) == ["JFK", "MUC", "LHR", "SFO", "SJC"]assert find_itinerary([["JFK", "KUL"], ["JFK", "NRT"], ["NRT", "JFK"]]) == ["JFK", "NRT", "JFK", "KUL"]print(find_itinerary([["JFK", "KUL"], ["JFK", "NRT"], ["NRT", "JFK"]]))
Output
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 the pairs0/6 matched

Match each problem to the technique that fits it best.

Choose an item, then its match on the other side.
Quick check
A graph has 6 nodes in one cycle: 0-1-2-3-4-5-0. You add one edge, 0-3. Is it still bipartite?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.