Skip to contentKEEP THE CRAFTTHE SANCTUARY

Cycle Detection

Choose cycle evidence to fit the graph model: an active directed DFS ancestor, a nonparent undirected revisit, or a repeated state in a one-successor chain. Do not confuse any prior visit with a cycle.

1 practice exercise3 interview problems

Recognize it when A dependency graph might prevent a complete topological order.

Checking your account…

Cycle Detection Code Labs

Match Detection to Graph Direction

Cycle evidence differs by graph model. A directed edge to an active ancestor is a cycle; an undirected edge back to the immediate parent is expected and must be excluded.

Track Active DFS Paths

Use three colors: unseen, active, and finished. Only an edge to active state is a directed back edge; an edge to a finished node may simply join a previously completed path.

Trace DFS Color Changes

Reference
def color_trace(adjacency,start):
    colors=[0]*len(adjacency);events=[]
    def visit(node):
        colors[node]=1;events.append([node,1])
        for neighbor in adjacency[node]:
            if colors[neighbor]==0:visit(neighbor)
        colors[node]=2;events.append([node,2])
    if start!=-1:visit(start)
    return events
Practice

Implement color_trace(adjacency,start). Return [node,color] events where color 1 enters the active path and 2 finishes.

Public tests

  • Separate active from finished nodes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace DFS Color Changes

def color_trace(adjacency,start):
    colors=[0]*len(adjacency);events=[]
    def visit(node):
        colors[node]=1;events.append([node,1])
        for neighbor in adjacency[node]:
            if colors[neighbor]==0:visit(neighbor)
        colors[node]=2;events.append([node,2])
    if start!=-1:visit(start)
    return events

A Finished Join Is Different from a Back Edge

The existing color trace is an event recorder. Predict its output for a DAG where node 2 is reached through node 1 and also directly from 0. That second edge illustrates why seen and active have different meanings.

Step Executed statement State Why
Enter root colors[node]=1;events.append([node,1]) node 0 active Only active frames belong to the current path.
Descend if colors[neighbor]==0:visit(neighbor) 0 -> 1 -> 2 become active The recursive branch records entry before exploring descendants.
Finish leaf colors[node]=2;events.append([node,2]) node 2 finished, then node 1 finished Return means all descendants of that frame were handled.
Root join edge if colors[neighbor]==0:visit(neighbor) neighbor 2 is color 2 and skipped The second route to 2 does not reenter an active ancestor.
Finish root colors[node]=2;events.append([node,2]) all reachable nodes finished This trace reveals a DAG join; the detection Lab returns False for the same graph.
Print Output
print(color_trace([[1, 2], [2], []], 0)) [[0, 1], [1, 1], [2, 1], [2, 2], [1, 2], [0, 2]]

For a self-loop, the detection Lab sees an edge back to its own active frame. For an undirected graph, a symmetric parent edge has a different meaning; do not reuse the directed test unchanged.

Detect a Directed Cycle

Reference
def has_directed_cycle(adjacency):
    colors=[0]*len(adjacency)
    def visit(node):
        colors[node]=1
        for neighbor in adjacency[node]:
            if colors[neighbor]==1:return True
            if colors[neighbor]==0 and visit(neighbor):return True
        colors[node]=2;return False
    return any(colors[node]==0 and visit(node) for node in range(len(adjacency)))
Practice

Implement has_directed_cycle(adjacency). Return whether any DFS reaches an active-path node.

Public tests

  • Detect only active-path back edges

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Detect a Directed Cycle

def has_directed_cycle(adjacency):
    colors=[0]*len(adjacency)
    def visit(node):
        colors[node]=1
        for neighbor in adjacency[node]:
            if colors[neighbor]==1:return True
            if colors[neighbor]==0 and visit(neighbor):return True
        colors[node]=2;return False
    return any(colors[node]==0 and visit(node) for node in range(len(adjacency)))

Use Parent Edges in Undirected Graphs

For undirected DFS, carry the parent and report a visited neighbor only when it is not that parent. Parallel-edge policy may require edge IDs rather than just parent nodes.

Choose Coloring Indegrees or Union Find

Use DFS coloring to locate directed cycle structure, Kahn’s processed count to test DAG feasibility, and union-find for cycles created by undirected edge additions. DFS coloring and queue-based Kahn are O(V + E). Union-find has an O(V + E alpha(V)) amortized aggregate bound with balancing and compression.

Explain It in an Interview

Say: “Visited means seen sometime; active means on the current recursion path. Only active-path edges close a directed cycle.” Identify the graph direction, disconnected components, self-loops, and the precise evidence your method returns.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Cycle Detection proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
DFS colors or FIFO Kahn detectionO(V + E)O(V + E)All components must be included.
Union-find undirected edge streamO(V + E alpha(V)) amortizedO(V + E alpha(V)) aggregateA different model from directed reachability.

Space

O(V) colors/frames beyond stored adjacency; the color-event trace has O(V) events.

Assumptions

  • A long DFS chain can exceed Python call depth; an explicit phased stack can preserve active/finished semantics.
  • The color-trace Lab records entry/exit events but does not itself report a cycle.

Invariants Worth Saying Aloud

  1. Color 1 marks only frames on the current active recursion path.
  2. Color 2 marks nodes whose outgoing exploration has finished.
  3. An edge to an active ancestor closes a real directed path back to that ancestor.

When To Use Or Avoid Cycle Detection

Use It When

  • Use active DFS colors for directed cycles and union-find for incremental undirected cycle closure.
  • Use fast/slow pointers only when each state has one deterministic successor.

Choose Another Tool When

  • A directed edge to a finished node can be harmless; seen alone is insufficient.
  • An undirected edge to the parent is expected, with special handling needed for parallel edges.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Treating any visited target as a directed cycle

A target with color 2 has completed a different branch. A cross edge to it does not close the current active path.

Prevent it: Report only color 1 as the directed back-edge condition.

Avoid

cycle = colors[neighbor] != 0

Use instead

cycle = colors[neighbor] == 1

Leaving a finished frame active

If node 1 stays color 1 after returning, a later branch joining it looks like a back edge.

Prevent it: Set color 2 only after all outgoing exploration is done.

Avoid

colors[node] = 1

Use instead

colors[node] = 2

Searching only the first component

The reachable component of node 0 can be acyclic while a disconnected component has a self-loop.

Prevent it: Start a new DFS from every unseen vertex.

Avoid

starts = [0] if colors[0] == 0 else []

Use instead

starts = [node for node, color in enumerate(colors) if color == 0]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.