Cycle Detection in Directed Graph in DSA C++ - Time & Space Complexity
We want to understand how long it takes to find a cycle in a directed graph.
The question is: how does the time needed grow as the graph gets bigger?
Analyze the time complexity of the following code snippet.
bool dfs(int node, vector<vector<int>>& graph, vector<int>& visited, vector<int>& recStack) {
visited[node] = 1;
recStack[node] = 1;
for (int neighbor : graph[node]) {
if (!visited[neighbor] && dfs(neighbor, graph, visited, recStack))
return true;
else if (recStack[neighbor])
return true;
}
recStack[node] = 0;
return false;
}
bool hasCycle(vector<vector<int>>& graph, int n) {
vector<int> visited(n, 0), recStack(n, 0);
for (int i = 0; i < n; i++) {
if (!visited[i] && dfs(i, graph, visited, recStack))
return true;
}
return false;
}
This code checks if a directed graph has a cycle using depth-first search and recursion.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node and exploring its neighbors recursively.
- How many times: Each node is visited once, and each edge is checked once during DFS.
As the graph grows, the time to check all nodes and edges grows roughly in proportion to their count.
| Input Size (n nodes) | Approx. Operations (nodes + edges) |
|---|---|
| 10 | About 10 nodes + edges checked once each |
| 100 | About 100 nodes + edges checked once each |
| 1000 | About 1000 nodes + edges checked once each |
Pattern observation: The work grows linearly with the number of nodes and edges combined.
Time Complexity: O(n + e)
This means the time grows linearly with the number of nodes (n) plus the number of edges (e) in the graph.
[X] Wrong: "The algorithm checks every possible path, so it takes exponential time."
[OK] Correct: Each node and edge is visited only once due to marking visited nodes, so the time is linear, not exponential.
Understanding this time complexity helps you explain how graph traversal algorithms scale, a key skill in many coding challenges.
"What if we changed the graph representation from adjacency list to adjacency matrix? How would the time complexity change?"
Practice
Solution
Step 1: Understand cycle in directed graph
A cycle means a path where you can start from a node and follow edges in their direction to come back to the same node.Step 2: Identify what cycle detection finds
Cycle detection checks if such a path exists anywhere in the graph.Final Answer:
Whether there is a path that starts and ends at the same node following edge directions -> Option AQuick Check:
Cycle detection = find directed loops [OK]
- Confusing cycle with shortest path
- Thinking cycle ignores edge directions
- Mixing cycle with node count
Solution
Step 1: Understand adjacency list declaration
For cycle detection, adjacency list is often a vector of vectors to store edges from each node.Step 2: Check each option
A: vector graph(100); - standard and flexible vector of vectors for adjacency list. B: adjacency matrix, not list. C: map, valid but less common and heavier for sequential nodes. D: array of vectors, works but fixed size and less modern than vector of vectors.Final Answer:
vector graph(100); -> Option AQuick Check:
Use vector of vectors for adjacency list [OK]
- Using adjacency matrix instead of list
- Confusing map with vector
- Using raw arrays limiting flexibility
bool dfs(int node, vector& graph, vector<int>& visited, vector<int>& recStack) {
visited[node] = 1;
recStack[node] = 1;
for (int adj : graph[node]) {
if (!visited[adj] && dfs(adj, graph, visited, recStack))
return true;
else if (recStack[adj])
return true;
}
recStack[node] = 0;
return false;
}
int main() {
vector graph(3);
graph[0].push_back(1);
graph[1].push_back(2);
graph[2].push_back(0);
vector<int> visited(3, 0), recStack(3, 0);
cout << (dfs(0, graph, visited, recStack) ? "Cycle Found" : "No Cycle") << endl;
return 0;
}Solution
Step 1: Analyze graph edges
Edges: 0->1, 1->2, 2->0 form a cycle (0->1->2->0).Step 2: Understand DFS cycle detection
DFS uses recursion stack to detect back edges indicating cycle. Here, cycle exists, so dfs returns true.Final Answer:
Cycle Found -> Option BQuick Check:
Cycle in 0->1->2->0 detected [OK]
- Ignoring recursion stack usage
- Assuming no cycle in simple loops
- Confusing visited and recursion stack arrays
bool dfs(int node, vector& graph, vector<bool>& visited, vector<bool>& recStack) {
visited[node] = true;
for (int adj : graph[node]) {
if (!visited[adj] && dfs(adj, graph, visited, recStack))
return true;
else if (recStack[adj])
return true;
}
recStack[node] = false;
return false;
}Solution
Step 1: Check usage of recStack
recStack marks nodes in current recursion path. It must be set true when node is entered.Step 2: Identify missing recStack[node] = true
Code sets recStack[node] = false at end but never sets it true at start, so cycle detection fails.Final Answer:
recStack[node] is never set to true at start -> Option DQuick Check:
Set recStack true on node entry [OK]
- Forgetting to set recStack true at start
- Confusing visited and recStack roles
- Wrong data types for visited array
Solution
Step 1: Analyze edges for cycles
Edges 1->2, 2->3, 3->1 form a cycle involving nodes 1, 2, 3.Step 2: Identify nodes outside cycle
Node 0 points to 1 but is not in cycle. Node 4 is only reached from 3 and has no outgoing edges back.Final Answer:
[1, 2, 3] -> Option CQuick Check:
Cycle nodes = 1, 2, 3 [OK]
- Including nodes only pointing into cycle
- Including nodes with no back edges
- Confusing cycle membership with reachability
Ready to prove it?
Pass the test and this pattern moves unknown
