Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Cycle Detection in Undirected Graph in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cycle Detection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of DFS-based cycle detection in undirected graph
What is the output of the following TypeScript code that detects a cycle in an undirected graph using DFS?
DSA Typescript
class Graph {
  adjacencyList: Map<number, number[]> = new Map();

  addEdge(u: number, v: number) {
    if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
    if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
    this.adjacencyList.get(u)!.push(v);
    this.adjacencyList.get(v)!.push(u);
  }

  hasCycle(): boolean {
    const visited = new Set<number>();

    const dfs = (node: number, parent: number): boolean => {
      visited.add(node);
      for (const neighbor of this.adjacencyList.get(node) || []) {
        if (!visited.has(neighbor)) {
          if (dfs(neighbor, node)) return true;
        } else if (neighbor !== parent) {
          return true;
        }
      }
      return false;
    };

    for (const node of this.adjacencyList.keys()) {
      if (!visited.has(node)) {
        if (dfs(node, -1)) return true;
      }
    }
    return false;
  }
}

const g = new Graph();
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 2);
console.log(g.hasCycle());
Atrue
Bfalse
Cundefined
DSyntaxError
Attempts:
2 left
💡 Hint
Think about whether the graph has a loop formed by edges.
🧠 Conceptual
intermediate
1:30remaining
Cycle detection condition in undirected graph DFS
In DFS cycle detection for an undirected graph, which condition correctly identifies a cycle?
AIf a neighbor is visited and is the parent of the current node, a cycle exists.
BIf a visited neighbor is not the parent of the current node, a cycle exists.
CIf a neighbor is unvisited, it means a cycle exists.
DIf the current node has no neighbors, a cycle exists.
Attempts:
2 left
💡 Hint
Think about how back edges indicate cycles in undirected graphs.
🔧 Debug
advanced
2:00remaining
Identify the error in cycle detection code
What error will this TypeScript code produce when detecting cycles in an undirected graph?
DSA Typescript
class Graph {
  adjacencyList: Map<number, number[]> = new Map();

  addEdge(u: number, v: number) {
    if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
    if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
    this.adjacencyList.get(u)!.push(v);
    this.adjacencyList.get(v)!.push(u);
  }

  hasCycle(): boolean {
    const visited = new Set<number>();

    const dfs = (node: number): boolean => {
      visited.add(node);
      for (const neighbor of this.adjacencyList.get(node) || []) {
        if (!visited.has(neighbor)) {
          if (dfs(neighbor)) return true;
        } else {
          return true;
        }
      }
      return false;
    };

    for (const node of this.adjacencyList.keys()) {
      if (!visited.has(node)) {
        if (dfs(node)) return true;
      }
    }
    return false;
  }
}
AThe code will incorrectly detect cycles due to missing parent tracking.
BThe code will cause a syntax error due to missing return statements.
CThe code will never detect any cycle because it returns false always.
DThe code will cause a runtime error due to undefined adjacency list.
Attempts:
2 left
💡 Hint
Check how the parent node is handled in DFS.
❓ Predict Output
advanced
2:00remaining
Output of BFS-based cycle detection in undirected graph
What is the output of this TypeScript code that detects a cycle in an undirected graph using BFS?
DSA Typescript
class Graph {
  adjacencyList: Map<number, number[]> = new Map();

  addEdge(u: number, v: number) {
    if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
    if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
    this.adjacencyList.get(u)!.push(v);
    this.adjacencyList.get(v)!.push(u);
  }

  hasCycle(): boolean {
    const visited = new Set<number>();

    for (const start of this.adjacencyList.keys()) {
      if (!visited.has(start)) {
        const queue: Array<[number, number]> = [[start, -1]];
        visited.add(start);

        while (queue.length > 0) {
          const [node, parent] = queue.shift()!;
          for (const neighbor of this.adjacencyList.get(node) || []) {
            if (!visited.has(neighbor)) {
              visited.add(neighbor);
              queue.push([neighbor, node]);
            } else if (neighbor !== parent) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
}

const g = new Graph();
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 5);
console.log(g.hasCycle());
Atrue
BTypeError
Cfalse
Dundefined
Attempts:
2 left
💡 Hint
Check if the graph edges form any cycle.
🧠 Conceptual
expert
1:30remaining
Why is parent tracking necessary in undirected graph cycle detection?
Why must we track the parent node when detecting cycles in an undirected graph using DFS or BFS?
ATo detect cycles only in directed graphs.
BTo improve the runtime complexity from exponential to linear.
CTo ensure all nodes are visited exactly once.
DTo avoid falsely detecting the immediate parent as a cycle neighbor.
Attempts:
2 left
💡 Hint
Think about the bidirectional edges in undirected graphs.

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

  1. Step 1: Understand DFS traversal in undirected graph

    DFS visits nodes and tracks the parent node to avoid false cycle detection.
  2. 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.
  3. Final Answer:

    If we visit a node that is already visited and is not the parent, a cycle exists. -> Option A
  4. 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

  1. Step 1: Identify required parameters for DFS cycle detection

    We need current node, parent node, visited array, and graph adjacency list.
  2. 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.
  3. Final Answer:

    function dfs(node: number, parent: number, visited: boolean[], graph: number[][]): boolean -> Option A
  4. Quick Check:

    DFS needs node, parent, visited, graph, returns boolean [OK]
Hint: DFS cycle detection needs parent node parameter [OK]
Common Mistakes:
  • Missing parent parameter causes incorrect cycle detection.
  • Wrong return type (void instead of boolean).
  • Using wrong node type (string instead of number).
3. What will be the output of the following TypeScript code snippet detecting cycle in an undirected graph?
const graph = [[1,2],[0,2],[0,1,3],[2]];
const visited = new Array(4).fill(false);
function dfs(node: number, parent: number): boolean {
  visited[node] = true;
  for (const neighbor of graph[node]) {
    if (!visited[neighbor]) {
      if (dfs(neighbor, node)) return true;
    } else if (neighbor !== parent) {
      return true;
    }
  }
  return false;
}
console.log(dfs(0, -1));
medium
A. undefined
B. true
C. false
D. Runtime Error

Solution

  1. Step 1: Analyze graph structure and DFS traversal

    Graph edges: 0-1, 0-2, 1-2, 2-3. Nodes 0,1,2 form a triangle (cycle).
  2. Step 2: Trace DFS calls from node 0

    DFS visits 0, then 1, then 2. At 2, neighbor 0 is visited and not parent, cycle detected, returns true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Triangle cycle detected = true [OK]
Hint: Triangle in graph means cycle detected true [OK]
Common Mistakes:
  • Ignoring parent check causes false cycle detection.
  • Assuming no cycle in triangle graph.
  • Confusing return values of DFS function.
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

  1. Step 1: Check recursive DFS call handling

    The recursive call dfs(neighbor, node, visited, graph) is made but its boolean result is ignored.
  2. Step 2: Identify missing return for cycle detection

    If recursive call returns true (cycle found), it should be returned immediately to propagate detection.
  3. Final Answer:

    Missing return statement for recursive dfs call result. -> Option C
  4. 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

  1. Step 1: Understand cycle detection with path tracking

    Maintain a stack or list of nodes visited in current DFS path to track traversal.
  2. 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.
  3. Final Answer:

    Track the path stack during DFS and return the cycle path when detected. -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard