← Back to Algorithms, page 4

algorithms-0071 · Medium mid

Cycle detection: decide whether a graph contains a cycle, once for an undirected graph and once for a directed graph, and explain why the two need different checks.

In an undirected graph, a DFS that reaches an already visited node through an edge other than the one it arrived on has found a cycle; union-find gives the same answer by checking whether an edge joins nodes already connected. In a directed graph, reaching a visited node is not enough: only an edge back to a node still on the current DFS path (grey) forms a cycle. All methods are O(V + E).

Full answer

Problem

Given n nodes and an edge list, return whether the graph contains a cycle. Solve it for an undirected graph and for a directed graph.

Example: undirected [(0,1), (1,2), (2,0)] has a cycle; directed [(0,1), (0,2), (1,2)] (a diamond) has none, even though node 2 is reached twice. A directed self-loop (0,0) is a cycle.

Constraints: up to 10^5 nodes and edges; parallel edges and self-loops may appear.

Brute force

Directed: try every ordering of nodes; the graph is acyclic exactly when some ordering puts every edge forward (O(n! * E)). Undirected: for each edge, remove it and test whether its endpoints are still connected (O(E * (V + E))).

Optimal approach

Undirected DFS: track the edge id used to reach each node; when scanning neighbours, skip the arriving edge and report a cycle if any other edge leads to a visited node. Tracking edge ids (not the parent node) makes a doubled edge u-v count as a cycle.

Directed DFS with three colours: white (unvisited), grey (on the current path), black (fully explored). An edge to a grey node is a back edge, which means a cycle. Edges to black nodes are fine.

Union-find (undirected only): an edge whose endpoints already share a root closes a cycle.

Why it works

Undirected: a DFS tree plus one more edge between already visited nodes always forms a cycle, because the two endpoints are already connected through the tree. Directed: a cycle exists exactly when DFS finds a back edge to an ancestor on the current path. An edge into a black node points to a finished subtree that cannot reach back to the current path, otherwise that node would not be finished. That is why the undirected check gives false positives on directed diamonds.

Complexity

O(V + E) time, O(V) space for all three methods (union-find is O(E * alpha(V))).

Code

python
import random
from itertools import permutations


def has_cycle_undirected(n, edges):
    """Iterative DFS that remembers each node's parent edge. O(V + E).
    Edge ids (not parent nodes) are tracked, so a duplicated edge u-v counts as a cycle."""
    adj = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        adj[u].append((v, i))
        adj[v].append((u, i))
    seen = [False] * n
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        stack = [(s, -1)]
        while stack:
            u, via = stack.pop()
            for v, eid in adj[u]:
                if eid == via:
                    continue             # do not walk straight back along the same edge
                if seen[v]:
                    return True
                seen[v] = True
                stack.append((v, eid))
    return False


def has_cycle_directed(n, edges):
    """Three colours: reaching a GREY node (on the current DFS path) means a back edge."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color = [WHITE] * n
    for s in range(n):
        if color[s] != WHITE:
            continue
        color[s] = GREY
        stack = [(s, iter(adj[s]))]
        while stack:
            u, it = stack[-1]
            v = next(it, None)
            if v is None:
                color[u] = BLACK
                stack.pop()
            elif color[v] == GREY:
                return True
            elif color[v] == WHITE:
                color[v] = GREY
                stack.append((v, iter(adj[v])))
    return False


def brute_undirected(n, edges):
    """A forest has exactly n - components edges; any extra edge makes a cycle."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            x = parent[x]
        return x
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            return True
        parent[ru] = rv
    return False


def brute_directed(n, edges):
    """Acyclic exactly when some ordering puts every edge forward."""
    return not any(all(p.index(u) < p.index(v) for u, v in edges) for p in permutations(range(n)))


if __name__ == "__main__":
    assert not has_cycle_undirected(4, [(0, 1), (1, 2), (2, 3)])
    assert has_cycle_undirected(3, [(0, 1), (1, 2), (2, 0)])
    assert has_cycle_undirected(2, [(0, 1), (0, 1)])          # parallel edges
    assert has_cycle_directed(3, [(0, 1), (1, 2), (2, 0)])
    assert not has_cycle_directed(3, [(0, 1), (0, 2), (1, 2)])  # diamond, not a cycle
    assert has_cycle_directed(1, [(0, 0)])
    rng = random.Random(71)
    for _ in range(500):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 7))]
        assert has_cycle_directed(n, es) == brute_directed(n, es)
        assert has_cycle_undirected(n, es) == brute_undirected(n, es)
    print("all tests passed")

Save as b71_cycle_detection.py and run python3 b71_cycle_detection.py. It prints all tests passed (Python 3.13.5).

Edge cases

Self-loops (cycle in both versions). Parallel undirected edges (cycle of length 2). Disconnected graphs (start a DFS from every unvisited node). Directed diamonds (no cycle). Deep graphs: the code uses explicit stacks.

Pattern

Back-edge detection in DFS. Directed cycle checks drive course schedule feasibility, deadlock detection in wait-for graphs, and dependency validation. Undirected cycle checks drive MST construction and "graph valid tree" (connected and E = V - 1).

python
import random
from itertools import permutations


def has_cycle_undirected(n, edges):
    """Iterative DFS that remembers each node's parent edge. O(V + E).
    Edge ids (not parent nodes) are tracked, so a duplicated edge u-v counts as a cycle."""
    adj = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        adj[u].append((v, i))
        adj[v].append((u, i))
    seen = [False] * n
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        stack = [(s, -1)]
        while stack:
            u, via = stack.pop()
            for v, eid in adj[u]:
                if eid == via:
                    continue             # do not walk straight back along the same edge
                if seen[v]:
                    return True
                seen[v] = True
                stack.append((v, eid))
    return False


def has_cycle_directed(n, edges):
    """Three colours: reaching a GREY node (on the current DFS path) means a back edge."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color = [WHITE] * n
    for s in range(n):
        if color[s] != WHITE:
            continue
        color[s] = GREY
        stack = [(s, iter(adj[s]))]
        while stack:
            u, it = stack[-1]
            v = next(it, None)
            if v is None:
                color[u] = BLACK
                stack.pop()
            elif color[v] == GREY:
                return True
            elif color[v] == WHITE:
                color[v] = GREY
                stack.append((v, iter(adj[v])))
    return False


def brute_undirected(n, edges):
    """A forest has exactly n - components edges; any extra edge makes a cycle."""
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            x = parent[x]
        return x
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            return True
        parent[ru] = rv
    return False


def brute_directed(n, edges):
    """Acyclic exactly when some ordering puts every edge forward."""
    return not any(all(p.index(u) < p.index(v) for u, v in edges) for p in permutations(range(n)))


if __name__ == "__main__":
    assert not has_cycle_undirected(4, [(0, 1), (1, 2), (2, 3)])
    assert has_cycle_undirected(3, [(0, 1), (1, 2), (2, 0)])
    assert has_cycle_undirected(2, [(0, 1), (0, 1)])          # parallel edges
    assert has_cycle_directed(3, [(0, 1), (1, 2), (2, 0)])
    assert not has_cycle_directed(3, [(0, 1), (0, 2), (1, 2)])  # diamond, not a cycle
    assert has_cycle_directed(1, [(0, 0)])
    rng = random.Random(71)
    for _ in range(500):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 7))]
        assert has_cycle_directed(n, es) == brute_directed(n, es)
        assert has_cycle_undirected(n, es) == brute_undirected(n, es)
    print("all tests passed")

Undirected DFS that skips only the arriving edge id, directed three-colour DFS, and brute force references (union-find and permutation search).

Complexity

Time: O(V + E). Space: O(V). Both DFS versions use explicit stacks, so recursion depth is not an issue.

By level

Fresher: Detects cycles in undirected graphs with DFS and a parent check, and explains why directed graphs need more care. Uses the diamond as an example.

Mid: Implements three-colour DFS for directed graphs and union-find for undirected ones. Handles parallel edges and returns the cycle when asked.

Senior: Discusses deadlock detection in wait-for graphs, incremental cycle checks as edges arrive, and cycle detection in very large dependency graphs. Connects back edges to strongly connected components.

Key points

  • Undirected: visited neighbour via a different edge means a cycle
  • Directed: edge to a grey node means a cycle
  • Black nodes are safe
  • Union-find works for undirected only
  • Start from every unvisited node

Common mistakes

  • Using the undirected rule on directed graphs
  • Skipping the parent node instead of the parent edge and missing parallel edges
  • Treating any visited node as a cycle in directed graphs
  • Only checking from node 0

Follow-ups

  • How would you return the actual cycle?
  • How do you check whether an undirected graph is a valid tree?
  • How would you detect deadlocks in a distributed system?

Tips

  • Explain why directed needs three colours
  • Draw the diamond counterexample
  • Mention union-find for undirected graphs

Evaluation rubric

  • Correct undirected and directed checks
  • Explains the difference
  • Handles self-loops and parallel edges
  • Correct complexity