Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Cycle Detection in Directed Graph in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Cycle Detection in Directed Graph
Start at each unvisited node
↓
Mark node as visited and in recursion stack
↓
For each neighbor
↓
If neighbor not visited
→Recurse DFS on neighbor
↓
If neighbor in recursion stack
→Cycle detected!
↓
Remove node from recursion stack
↓
Repeat for all nodes
↓
No cycle found if all done
We visit each node, track recursion stack to find back edges indicating cycles.
Execution Sample
DSA Javascript
function dfs(node) {
  visited[node] = true;
  recStack[node] = true;
  for (let neighbor of graph[node]) {
    if (!visited[neighbor] && dfs(neighbor)) return true;
    else if (recStack[neighbor]) return true;
  }
  recStack[node] = false;
  return false;
}
This code runs DFS to detect cycles by tracking nodes in the recursion stack.
Execution Table
StepOperationCurrent NodeVisited SetRecursion StackActionCycle DetectedGraph State
1Start DFS at node 00[0][0]Mark 0 visited and in stackNo0 -> [1,2], 1 -> [2], 2 -> [0,3], 3 -> []
2Visit neighbor 1 of 01[0,1][0,1]Mark 1 visited and in stackNoSame as above
3Visit neighbor 2 of 12[0,1,2][0,1,2]Mark 2 visited and in stackNoSame as above
4Visit neighbor 0 of 20[0,1,2][0,1,2]0 is in recursion stack -> cycle foundYesSame as above
5Cycle detected, stop DFS-[0,1,2][0,1,2]Return true up call stackYesSame as above
💡 Cycle detected when visiting node 0 again while it is in recursion stack
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
visited[][0][0,1][0,1,2][0,1,2][0,1,2]
recStack[][0][0,1][0,1,2][0,1,2][0,1,2]
currentNodenull01200
cycleDetectedfalsefalsefalsefalsetruetrue
Key Moments - 3 Insights
Why do we check if a neighbor is in the recursion stack to detect a cycle?
Because a node in the recursion stack means we are visiting it again before finishing its DFS, indicating a back edge and thus a cycle. See step 4 in execution_table where visiting node 0 again while in stack detects cycle.
Why do we need both 'visited' and 'recursion stack' arrays?
'visited' tracks all nodes ever visited to avoid reprocessing, while 'recursion stack' tracks nodes in the current DFS path to detect cycles. Step 2 and 3 show nodes added to both, step 5 shows cycle detection using recursion stack.
What happens if the graph has no cycles?
The DFS finishes visiting all nodes without finding any neighbor in the recursion stack, so cycleDetected remains false. The recursion stack empties as DFS backtracks.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, which nodes are currently in the recursion stack?
A[1, 2]
B[0, 1, 2]
C[0, 1]
D[2]
💡 Hint
Check the 'Recursion Stack' column at step 3 in execution_table.
At which step does the cycle get detected according to the execution_table?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for 'Cycle Detected' column showing 'Yes' first time.
If the graph had no edges, how would the 'visited' array change after DFS on node 0?
A[0]
B[]
C[0,1,2]
D[1]
💡 Hint
Refer to variable_tracker for 'visited' changes after first step.
Concept Snapshot
Cycle Detection in Directed Graph using DFS
- Use two arrays: visited and recursion stack
- DFS marks node visited and adds to recursion stack
- If neighbor is in recursion stack, cycle exists
- Remove node from recursion stack after DFS call
- Stops immediately when cycle found
Full Transcript
Cycle detection in a directed graph uses depth-first search (DFS). We keep track of nodes visited and nodes currently in the recursion stack (the current path). Starting from each unvisited node, we mark it visited and add it to the recursion stack. For each neighbor, if it is not visited, we recurse DFS on it. If the neighbor is already in the recursion stack, it means we found a cycle. We then stop and return true. After exploring all neighbors, we remove the node from the recursion stack. This process repeats for all nodes. The key is that a back edge to a node in the recursion stack signals a cycle. The execution table shows a graph with nodes 0,1,2,3 and edges forming a cycle 0->1->2->0. The variable tracker shows how visited and recursion stack arrays change step by step. The key moments clarify why recursion stack is needed and how cycle detection works. The visual quiz tests understanding of recursion stack state and cycle detection step. The snapshot summarizes the approach in simple steps.

Practice

(1/5)
1. What is the main purpose of cycle detection in a directed graph?
easy
A. To find if there is a path that starts and ends at the same node following the direction of edges
B. To count the total number of edges in the graph
C. To find the shortest path between two nodes
D. To check if the graph is connected

Solution

  1. Step 1: Understand cycle in directed graph

    A cycle means a path that starts and ends at the same node following edge directions.
  2. Step 2: Purpose of cycle detection

    Cycle detection checks if such a path exists in the graph.
  3. Final Answer:

    To find if there is a path that starts and ends at the same node following the direction of edges -> Option A
  4. Quick Check:

    Cycle detection = find directed loops [OK]
Hint: Cycle means a directed loop returning to start [OK]
Common Mistakes:
  • Confusing cycle detection with counting edges
  • Thinking cycle detection finds shortest paths
  • Assuming cycle detection checks connectivity
2. Which of the following JavaScript code snippets correctly initializes a graph as an adjacency list for cycle detection?
easy
A. const graph = {0: [1, 2], 1: [2], 2: [0]};
B. const graph = [[0,1], [1,2], [2,0]];
C. const graph = new Map([0, [1, 2], 1, [2], 2, [0]]);
D. const graph = {0 => [1, 2], 1 => [2], 2 => [0]};

Solution

  1. Step 1: Check adjacency list syntax in JavaScript

    An adjacency list is an object with keys as nodes and values as arrays of neighbors.
  2. Step 2: Validate each option

    const graph = {0: [1, 2], 1: [2], 2: [0]}; uses correct object syntax with arrays as values. const graph = [[0,1], [1,2], [2,0]]; is an edge list, not adjacency list. const graph = new Map([0, [1, 2], 1, [2], 2, [0]]); uses Map incorrectly (missing array of pairs). const graph = {0 => [1, 2], 1 => [2], 2 => [0]}; uses invalid arrow syntax in object keys.
  3. Final Answer:

    const graph = {0: [1, 2], 1: [2], 2: [0]}; -> Option A
  4. Quick Check:

    Object with arrays = adjacency list [OK]
Hint: Adjacency list uses object keys with array values [OK]
Common Mistakes:
  • Using edge list instead of adjacency list
  • Incorrect Map initialization syntax
  • Using invalid object key syntax
3. Consider the following JavaScript code for cycle detection in a directed graph using DFS:
const graph = {0: [1], 1: [2], 2: [0]};
const visited = new Set();
const recStack = new Set();

function dfs(node) {
  if (recStack.has(node)) return true;
  if (visited.has(node)) return false;
  visited.add(node);
  recStack.add(node);
  for (const neighbor of graph[node] || []) {
    if (dfs(neighbor)) return true;
  }
  recStack.delete(node);
  return false;
}

console.log(dfs(0));
What will be printed when this code runs?
medium
A. false
B. true
C. undefined
D. TypeError

Solution

  1. Step 1: Trace DFS calls starting from node 0

    Start at 0: visited={0}, recStack={0}. Visit neighbor 1: visited={0,1}, recStack={0,1}. Visit neighbor 2: visited={0,1,2}, recStack={0,1,2}. Visit neighbor 0 again: recStack has 0, so return true (cycle found).
  2. Step 2: Return true up the call stack

    Since cycle detected, dfs returns true and console.log prints true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Cycle detected = true [OK]
Hint: Cycle if node revisited in recursion stack [OK]
Common Mistakes:
  • Ignoring recursion stack and returning false
  • Confusing visited set with recursion stack
  • Expecting false because all nodes visited
4. The following code attempts to detect a cycle in a directed graph but does not work correctly. What is the main error?
const graph = {0: [1], 1: [2], 2: [0]};
const visited = new Set();

function dfs(node) {
  if (visited.has(node)) return false;
  visited.add(node);
  for (const neighbor of graph[node] || []) {
    if (dfs(neighbor)) return true;
  }
  return false;
}

console.log(dfs(0));
medium
A. Visited set is not cleared after recursion
B. Function does not return any value
C. Graph adjacency list is incorrectly defined
D. Missing recursion stack to detect back edges

Solution

  1. Step 1: Analyze cycle detection logic

    The code uses only a visited set but no recursion stack to track nodes in current path.
  2. Step 2: Understand why recursion stack is needed

    Without recursion stack, the code cannot detect back edges that form cycles, so it misses cycles.
  3. Final Answer:

    Missing recursion stack to detect back edges -> Option D
  4. Quick Check:

    Recursion stack needed for cycle detection [OK]
Hint: Use recursion stack to detect cycles in DFS [OK]
Common Mistakes:
  • Assuming visited set alone detects cycles
  • Not tracking nodes in current recursion path
  • Confusing visited set clearing with cycle detection
5. You have a directed graph represented as an adjacency list:
const graph = {
  0: [1],
  1: [2, 3],
  2: [4],
  3: [4],
  4: [1]
};
Which of the following modifications will break the cycle detection algorithm that uses DFS with a recursion stack?
hard
A. Starting DFS from node 0 instead of node 4
B. Adding a visited set to track visited nodes
C. Removing the recursion stack and using only a visited set
D. Using an iterative BFS instead of DFS

Solution

  1. Step 1: Understand the role of recursion stack in cycle detection

    The recursion stack tracks nodes in the current path to detect cycles (back edges).
  2. Step 2: Effect of removing recursion stack

    Without recursion stack, the algorithm cannot detect cycles correctly, even if visited set is used.
  3. Step 3: Other options explained

    Adding visited set helps. Starting DFS from different nodes does not break detection if all nodes are visited. Using BFS does not detect cycles in directed graphs reliably.
  4. Final Answer:

    Removing the recursion stack and using only a visited set -> Option C
  5. Quick Check:

    Recursion stack needed for cycle detection [OK]
Hint: Recursion stack is essential for detecting cycles in DFS [OK]
Common Mistakes:
  • Thinking visited set alone detects cycles
  • Believing BFS can replace DFS for cycle detection
  • Assuming start node affects cycle detection correctness
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard