0
0
DSA Typescriptprogramming~20 mins

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

Choose your learning style9 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.