Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Graphs and connections
EXPERIMENT 39 / 66

Spot the route back into the route.

Distinguish visited vertices from vertices still active on the current DFS path.

BY NAVAN SAMI◷ 9 MIN READCOREALGORITHM

01 Model the idea

In a directed graph, an edge into the active DFS path proves a cycle. An edge to a previously completed vertex does not necessarily do so. Three states—unseen, active, complete—capture that distinction. Explore every component, not just one start vertex, when the question asks whether the entire graph contains a cycle.

THE THING THAT MUST STAY TRUE

Active vertices are exactly the unfinished DFS path.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
MARK a vertex active on entry
REJECT an edge to an active vertex
MARK the vertex complete on exit

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

graph_cycles.py
def has_cycle(graph):
    state = {node: 0 for node in graph}
    def visit(node):
        state[node] = 1
        for neighbour in graph[node]:
            if state[neighbour] == 1: return True
            if state[neighbour] == 0 and visit(neighbour): return True
        state[node] = 2
        return False
    return any(state[node] == 0 and visit(node) for node in graph)
print(has_cycle({"A": ["B"], "B": ["C"], "C": ["A"]}))
print(has_cycle({"A": ["B", "C"], "B": ["C"], "C": []}))
↳ EXPECTED OUTPUT
True
False
  1. 1

    An active vertex has been entered but not completed. A back edge into that path closes a directed loop.

  2. 2

    The second fixture has multiple routes to C but no directed cycle. Treating every edge to a visited vertex as a cycle would be wrong.

  3. 3

    This recursive implementation can exceed Python’s depth limit on a long path. Use an explicit stack with entry/exit state for deep production graphs. Every referenced neighbour must appear in the vertex map.

04 Count the cost

TIME

O(V + E)

SPACE

O(V) state and recursion stack

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Use a topological-processing baseline to recognise a directed cycle.

Reveal one possible solution +
one_possible_solution.py
from collections import deque
def has_cycle(graph):
    degree = {node: 0 for node in graph}
    for neighbours in graph.values():
        for node in neighbours: degree[node] += 1
    queue = deque(node for node in graph if degree[node] == 0)
    removed = 0
    while queue:
        node = queue.popleft(); removed += 1
        for neighbour in graph[node]:
            degree[neighbour] -= 1
            if degree[neighbour] == 0: queue.append(neighbour)
    return removed != len(graph)
print(has_cycle({"A": ["B"], "B": ["A"]}))

06 Check your reasoning

QUICK SIGNAL CHECK

Which directed DFS edge proves a cycle?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.