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)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 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.
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.
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 eventsImplement color_trace(adjacency,start). Return [node,color] events where color 1 enters the active path and 2 finishes.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 eventsThe 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. |
| 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.
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)))Implement has_directed_cycle(adjacency). Return whether any DFS reaches an active-path node.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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)))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.
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.
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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| DFS colors or FIFO Kahn detection | O(V + E) | O(V + E) | All components must be included. |
| Union-find undirected edge stream | O(V + E alpha(V)) amortized | O(V + E alpha(V)) aggregate | A different model from directed reachability. |
O(V) colors/frames beyond stored adjacency; the color-event trace has O(V) events.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
cycle = colors[neighbor] != 0cycle = colors[neighbor] == 1Where you will hit this: Detect a Directed Cycle(opens in a new tab)
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.
colors[node] = 1colors[node] = 2Where you will hit this: Detect a Directed Cycle(opens in a new tab)
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.
starts = [0] if colors[0] == 0 else []starts = [node for node, color in enumerate(colors) if color == 0]Where you will hit this: Find the Duplicate Number(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27
python-docs · checked 2026-07-27