📖 Scenario: Imagine you are working on a network of friends where each friend is connected to others. You want to check if there is any circle of friends where you can start from one friend and come back to the same friend by following connections without repeating edges.
🎯 Goal: You will build a program to detect if there is a cycle in an undirected graph using adjacency lists and depth-first search.
📋 What You'll Learn
Create an adjacency list to represent the graph
Use a helper array to track visited nodes
Implement a depth-first search function to detect cycles
Print true if a cycle exists, otherwise false
💡 Why This Matters
🌍 Real World
Cycle detection helps find loops in networks like social connections, computer networks, or road maps to avoid repeated paths or errors.
💼 Career
Understanding cycle detection is important for software engineers working on graph algorithms, network analysis, and debugging complex data structures.
Progress0 / 4 steps
1
Create the graph adjacency list
Create a variable called graph as an object representing the adjacency list with these exact entries: 0: [1, 2], 1: [0, 2], 2: [0, 1, 3], 3: [2]
DSA Typescript
Hint
Use an object where keys are node numbers and values are arrays of connected nodes.
2
Create a visited array
Create a variable called visited as an array of booleans with length 4, initialized with false values
DSA Typescript
Hint
Use an array with four false values to mark nodes as not visited yet.
3
Implement DFS function to detect cycle
Write a function called dfs that takes node and parent as parameters. Inside, mark visited[node] as true. Then loop over neighbors in graph[node]. If a neighbor is not visited, recursively call dfs with neighbor and current node. If a neighbor is visited and not equal to parent, return true. Return false if no cycle found.
DSA Typescript
Hint
Use recursion to visit neighbors and check if a visited neighbor is not the parent to detect a cycle.
4
Check for cycle and print result
Write code to loop over nodes 0 to 3. If visited[node] is false, call dfs(node, -1). If dfs returns true, print true and stop. If no cycle found after loop, print false.
DSA Typescript
Hint
Loop through all nodes and call dfs if not visited. Print true if cycle found, else false.
Practice
(1/5)
1. What is the main idea behind detecting a cycle in an undirected graph using DFS?
easy
A. If we visit a node that is already visited and is not the parent, a cycle exists.
B. If the graph has more edges than nodes, it always has a cycle.
C. If all nodes are visited exactly once, there is a cycle.
D. If the graph is disconnected, it contains a cycle.
Solution
Step 1: Understand DFS traversal in undirected graph
DFS visits nodes and tracks the parent node to avoid false cycle detection.
Step 2: Detect cycle condition
If during DFS, a visited node is found that is not the parent, it means a back edge exists, indicating a cycle.
Final Answer:
If we visit a node that is already visited and is not the parent, a cycle exists. -> Option A
Quick Check:
Cycle detection = visit visited node not parent [OK]
Hint: Check visited nodes excluding parent during DFS for cycle [OK]
Common Mistakes:
Ignoring the parent node check causes false positives.
Assuming more edges than nodes always means cycle.
Confusing disconnected graph with cycle presence.
2. Which of the following TypeScript function signatures correctly represents a DFS function for cycle detection in an undirected graph?
easy
A. function dfs(node: number, parent: number, visited: boolean[], graph: number[][]): boolean
B. function dfs(node: string, graph: number[][]): void
C. function dfs(visited: boolean[], graph: number[][]): number
D. function dfs(node: number, graph: number[][]): boolean
Solution
Step 1: Identify required parameters for DFS cycle detection
We need current node, parent node, visited array, and graph adjacency list.
Step 2: Match function signature with parameters and return type
function dfs(node: number, parent: number, visited: boolean[], graph: number[][]): boolean has all parameters and returns boolean indicating cycle presence.
Final Answer:
function dfs(node: number, parent: number, visited: boolean[], graph: number[][]): boolean -> Option A
4. Identify the bug in the following TypeScript code for cycle detection in an undirected graph:
function dfs(node: number, parent: number, visited: boolean[], graph: number[][]): boolean {
visited[node] = true;
for (const neighbor of graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, node, visited, graph);
} else if (neighbor !== parent) {
return true;
}
}
return false;
}
medium
A. Visited array is not updated correctly.
B. Parent parameter is not used in the function.
C. Missing return statement for recursive dfs call result.
D. Graph adjacency list is not passed correctly.
Solution
Step 1: Check recursive DFS call handling
The recursive call dfs(neighbor, node, visited, graph) is made but its boolean result is ignored.
Step 2: Identify missing return for cycle detection
If recursive call returns true (cycle found), it should be returned immediately to propagate detection.
Final Answer:
Missing return statement for recursive dfs call result. -> Option C
Quick Check:
Return recursive DFS result to detect cycle [OK]
Hint: Always return recursive DFS result for cycle detection [OK]
Common Mistakes:
Ignoring return value of recursive DFS calls.
Not updating visited array before recursion.
Misusing parent parameter in cycle check.
5. Given an undirected graph represented as an adjacency list, how can you modify the cycle detection algorithm to also return the nodes forming the cycle?
hard
A. Mark nodes visited twice to identify cycle nodes.
B. Use BFS instead of DFS to find cycles and record nodes.
C. Count edges and nodes; if edges > nodes, return all nodes as cycle.
D. Track the path stack during DFS and return the cycle path when detected.
Solution
Step 1: Understand cycle detection with path tracking
Maintain a stack or list of nodes visited in current DFS path to track traversal.
Step 2: Return cycle nodes when back edge found
When a visited node (not parent) is found, extract nodes from stack forming the cycle path.
Final Answer:
Track the path stack during DFS and return the cycle path when detected. -> Option D
Quick Check:
Use DFS path stack to get cycle nodes [OK]
Hint: Use DFS path stack to capture cycle nodes [OK]
Common Mistakes:
Using BFS which is less natural for cycle path retrieval.
Assuming edge count alone identifies cycle nodes.
Marking nodes visited twice without path context.
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.