Introduction
In our last lesson on the Bellman-Ford algorithm, we saw how to detect a specific type of cycle: one with a negative total weight. This was a critical feature, as such cycles render the concept of a "shortest path" meaningless.
Today, we'll generalize this problem. We'll learn how to detect the mere presence of any cycle in a graph, regardless of edge weights. This is a fundamental capability with wide-ranging applications, from resolving dependencies in a build system (e.g., ensuring A doesn't depend on B if B depends on A) to finding deadlocks in concurrent systems.
Our tool for this task will be Depth-First Search (DFS). You will learn how to apply DFS-based techniques to detect cycles in both directed and undirected graphs. The strategies for each are subtly different but equally important to master for an interview setting.
The Core Principle: DFS and Back Edges
The fundamental idea behind using DFS for cycle detection is identifying a "back edge". A back edge is an edge that leads from a node to one of its ancestors in the DFS traversal tree. If you can follow a path down the tree and then take a single edge back up to a node you've already seen on that same path, you have found a cycle.

Our task is to devise a systematic way to use DFS to find these back edges. As we will see, the method for doing this differs slightly between directed and undirected graphs.
For a formal definition of back edges and how they relate to cycles, let's consult a short article on the topic. This will provide the theoretical foundation for our algorithms.
Read the sections 'Cycle in a Graph', 'Detect Cycle using DFS', 'Types of Edges in DFS', and 'Back Edges → Cycle'. This will take about 2-3 minutes and will clarify why finding a back edge is equivalent to finding a cycle.
Detecting Cycles in Directed Graphs
In a directed graph, we need to distinguish between visiting a node that's truly an ancestor in our current path versus visiting a node that was part of a different, already completed DFS path.
To do this, we use a three-state (or "three-color") system for each node:
- WHITE (Unvisited): The node has not been discovered yet.
- GREY (Visiting): The node has been discovered and is currently in our recursion stack. We are actively exploring its neighbors.
- BLACK (Visited): The node and all of its descendants have been fully explored.
A cycle is detected when, during a DFS traversal, we encounter a GREY node. This means we've found a back edge to a node that is currently in our recursion stack—an ancestor.
Cycle Detection for Directed and Undirected Graphs in Java | Check if a Graph has a Cycle | Geekific
This video provides an excellent visual explanation of the three-state system in action. The narrator uses 'green' for our GREY state (visiting) and 'blue' for our BLACK state (visited).
Watch from 00:28 to 05:57. First, focus on the conceptual walkthrough (until 03:27) to see how encountering a 'green' (GREY) node signals a cycle. Then, observe how this logic is translated into a recursive function with beingVisited and visited flags.
Handling Disconnected Graphs
A crucial edge case in interviews is the disconnected graph. If we only start DFS from a single source, we might miss a cycle in an entirely separate component of the graph. The solution is to iterate through all vertices. If a vertex hasn't been visited yet (is still WHITE), we initiate a new DFS traversal from it. The video segment you just watched (starting around 05:57) also covers this exact point.
Detecting Cycles in Undirected Graphs
You might wonder: why not just use the same three-color system for undirected graphs?
In an undirected graph, every edge (u, v) is bidirectional. When we traverse from u to v, u is marked GREY. From v, one of its neighbors is u. Since u is GREY, our previous logic would immediately (and incorrectly) detect a cycle u-v-u.
To handle this, we simplify our approach. We only need two states (visited/unvisited), but we must also keep track of the parent node that called the current DFS function.
The rule for cycle detection becomes: If DFS from node u encounters a neighbor v that is already visited AND v is not the immediate parent of u, we have found a cycle.

G-12. Detect a Cycle in an Undirected Graph using DFS | C++ | Java
This next video provides a very clear, step-by-step dry run of this parent-tracking DFS method for an undirected graph.
Watch from 00:56 to 08:24. Pay close attention to how the parent parameter is used to distinguish between simply going back to the node you just came from and finding a true back edge to a non-parent ancestor.
Go Implementation and Staff-Level Analysis
As a senior engineer, you're expected to produce clean, correct code and analyze it thoroughly. Let's look at idiomatic Go implementations for both scenarios.
A common representation for a graph in Go is an adjacency list, which we can implement as a map[int][]int.
Directed Graph Cycle Detection (Go)
package main
// State representation for each node
const (
WHITE = 0 // Unvisited
GREY = 1 // Visiting
BLACK = 2 // Visited
)
// hasCycleDirected checks for a cycle in a single DFS traversal.
// It returns true if a cycle is found.
func hasCycleDirected(node int, adj map[int][]int, colors map[int]int) bool {
colors[node] = GREY // Mark current node as visiting
for _, neighbor := range adj[node] {
if colors[neighbor] == GREY {
// Found a back edge to a node in the current recursion stack
return true
}
if colors[neighbor] == WHITE {
if hasCycleDirected(neighbor, adj, colors) {
return true
}
}
// If neighbor is BLACK, it's a cross-edge or forward-edge.
// It's part of a path we've already fully explored and verified as acyclic.
}
colors[node] = BLACK // Mark as fully visited
return false
}
// IsCyclicDirected is the main function to handle disconnected graphs.
func IsCyclicDirected(numNodes int, adj map[int][]int) bool {
colors := make(map[int]int)
for i := 0; i < numNodes; i++ {
colors[i] = WHITE
}
for i := 0; i < numNodes; i++ {
if colors[i] == WHITE {
if hasCycleDirected(i, adj, colors) {
return true
}
}
}
return false
}
Undirected Graph Cycle Detection (Go)
package main
// hasCycleUndirected checks for a cycle using parent tracking.
// It returns true if a cycle is found.
func hasCycleUndirected(node int, parent int, adj map[int][]int, visited map[int]bool) bool {
visited[node] = true
for _, neighbor := range adj[node] {
if neighbor == parent {
// This is the edge back to where we just came from, ignore it.
continue
}
if visited[neighbor] {
// Found a visited node that is not our parent. Cycle detected.
return true
}
if hasCycleUndirected(neighbor, node, adj, visited) {
return true
}
}
return false
}
// IsCyclicUndirected is the main function to handle disconnected graphs.
func IsCyclicUndirected(numNodes int, adj map[int][]int) bool {
visited := make(map[int]bool)
for i := 0; i < numNodes; i++ {
if !visited[i] {
// The initial call has no parent, so we can use a value like -1.
if hasCycleUndirected(i, -1, adj, visited) {
return true
}
}
}
return false
}
Complexity and Trade-offs
- Time Complexity: for both algorithms. The DFS process visits each vertex (
V) and each edge (E) at most once across all traversals. - Space Complexity: . This is for storing the color/visited status of each vertex. In the worst case (a long, chain-like graph), the recursion stack depth can also be .
Follow-up: Printing the Cycle
A common follow-up question at a Staff+ level is: "You've detected a cycle. Can you modify your code to print one such cycle?"
This can be achieved by storing the parent of each node during the DFS traversal.
- When you detect a cycle (e.g., from node
uto an already-visited nodev),vis the "start" of the cycle anduis the "end". - You can then reconstruct the cycle path by starting at
uand backtracking using theparentpointers until you reachvagain. - Reverse the collected path to get the cycle in traversal order.
The resource from cp-algorithms.com (LINK) contains C++ implementations under the "Implementation" sections that demonstrate exactly this logic for both directed and undirected graphs if you wish to see it in code.
Conclusion
In this lesson, we established a robust framework for detecting cycles in graphs using Depth-First Search. This is a classic algorithm that serves as a building block for many other graph-related problems.
Key Takeaways:
- A cycle corresponds to a back edge in a DFS traversal.
- For directed graphs, use a three-state system (e.g., WHITE, GREY, BLACK) to track node status. A cycle exists if you encounter a GREY node.
- For undirected graphs, a simpler two-state system (visited/unvisited) combined with parent tracking is used. A cycle exists if you encounter a visited node that is not your immediate parent.
- The overall time complexity for both approaches is , as it's based on a full graph traversal.
- Always consider the case of disconnected graphs in your main function by iterating through all vertices.
This lesson is a direct prerequisite for our next topic: Topological Sort. A topological sort provides a linear ordering of vertices in a graph such that for every directed edge from u to v, u comes before v in the ordering. As you might guess, such an ordering is only possible if the graph has no directed cycles. We will use the algorithm we just learned to first verify that a graph is a Directed Acyclic Graph (DAG) before attempting to sort it.