Cycle Detection in Directed Graph in DSA Typescript - Time & Space Complexity
We want to understand how long it takes to check if a directed graph has a cycle.
This helps us know how the work grows as the graph gets bigger.
Analyze the time complexity of the following code snippet.
function hasCycle(graph: Map<number, number[]>): boolean {
const visited = new Set<number>();
const recStack = new Set<number>();
function dfs(node: number): boolean {
if (recStack.has(node)) return true;
if (visited.has(node)) return false;
visited.add(node);
recStack.add(node);
for (const neighbor of graph.get(node) || []) {
if (dfs(neighbor)) return true;
}
recStack.delete(node);
return false;
}
for (const node of graph.keys()) {
if (dfs(node)) return true;
}
return false;
}
This code checks if a directed graph has a cycle using depth-first search and tracking recursion stack.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Depth-first search (DFS) visits each node and its neighbors.
- How many times: Each node is visited once, and each edge is checked once during DFS.
As the number of nodes and edges grow, the work grows roughly in proportion to their total.
| Input Size (n nodes, e edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 operations (visiting nodes + edges) |
| 100 nodes, 200 edges | About 300 operations |
| 1000 nodes, 5000 edges | About 6000 operations |
Pattern observation: The operations grow roughly linearly with the sum of nodes and edges.
Time Complexity: O(n + e)
This means the time to detect a cycle grows linearly with the number of nodes plus edges in the graph.
[X] Wrong: "The DFS visits nodes multiple times, so time is O(n * e)."
[OK] Correct: Each node is marked visited and processed once, so edges are checked only once, keeping time linear.
Understanding this time complexity helps you explain how your cycle detection scales with graph size, a key skill in graph problems.
"What if we used an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand cycle in directed graph
A cycle means a path that starts and ends at the same node following the direction of edges.Step 2: Identify what cycle detection finds
Cycle detection checks if such a path exists 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 = finding directed loops [OK]
- Confusing cycle with shortest path
- Ignoring edge directions
- Thinking cycle means any repeated node without direction
Solution
Step 1: Identify recursion stack tracking
We need to quickly check if a node is in the current recursion path.Step 2: Choose data structure for fast membership check
A Set allows O(1) membership check, ideal for tracking nodes in recursion stack.Final Answer:
Set -> Option DQuick Check:
Recursion stack tracking uses Set [OK]
- Using Array and checking membership with loops (slow)
- Using Queue which is FIFO, not suitable here
- Using Map without key-value need
const graph = new Map([
[1, [2]],
[2, [3]],
[3, [1]]
]);
function hasCycle(node: number, visited: Set<number>, recStack: Set<number>): boolean {
if (!visited.has(node)) {
visited.add(node);
recStack.add(node);
for (const neighbor of graph.get(node) || []) {
if (!visited.has(neighbor) && hasCycle(neighbor, visited, recStack)) {
return true;
} else if (recStack.has(neighbor)) {
return true;
}
}
}
recStack.delete(node);
return false;
}
console.log(hasCycle(1, new Set(), new Set()));Solution
Step 1: Analyze graph edges
Graph edges: 1->2, 2->3, 3->1 form a cycle.Step 2: Trace recursion and cycle detection
Starting at 1, recursion visits 2, then 3, then back to 1 which is in recursion stack, so returns true.Final Answer:
true -> Option CQuick Check:
Cycle exists in 1->2->3->1 path [OK]
- Ignoring recursion stack check
- Assuming no cycle if visited is true
- Confusing visited and recursion stack sets
function detectCycle(node: number, visited: Set<number>, recStack: Set<number>): boolean {
if (visited.has(node)) {
return false;
}
visited.add(node);
recStack.add(node);
for (const neighbor of graph.get(node) || []) {
if (detectCycle(neighbor, visited, recStack)) {
return true;
}
}
recStack.delete(node);
return false;
}Solution
Step 1: Review cycle detection logic
Cycle detection requires checking if neighbor is already in recursion stack to detect back edge.Step 2: Identify missing condition
The code calls recursion but does not check if neighbor is in recStack, so misses cycles.Final Answer:
Missing check if neighbor is in recursion stack to detect cycle -> Option AQuick Check:
Check recStack for back edges to detect cycles [OK]
- Skipping recursion stack membership check
- Confusing visited and recursion stack roles
- Not removing node from recursion stack after recursion
const graph = new Map([ [1, [2, 3]], [2, [4]], [3, [4, 5]], [4, [6]], [5, [3]], [6, []] ]);Which nodes are part of at least one cycle?
Solution
Step 1: Analyze edges for cycles
Edges: 3->5 and 5->3 form a cycle between nodes 3 and 5.Step 2: Check other nodes
Nodes 1, 2, 4, 6 do not form cycles as no back edges lead to them.Final Answer:
[3, 5] -> Option BQuick Check:
Cycle nodes = 3 and 5 only [OK]
- Including nodes not in any cycle
- Missing nodes that form cycles
- Confusing path with cycle
Ready to prove it?
Pass the test and this pattern moves unknown
