Detect Cycle in Undirected Graph (BFS) Problem

Detect Cycle in Undirected Graph (BFS) Problem — ExecCode Medium DSA Practice

Solve the Detect Cycle in Undirected Graph (BFS) problem on ExecCode. Free online medium DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.

Problem description

Given n nodes (0..n-1) and an undirected edge list, return true if the graph contains a cycle. Use BFS and track each node's parent so the immediate back-edge to the parent is ignored.

Examples

Input n = 6, edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 5]]; Output true. Input n = 4, edges = [[0, 1], [1, 2], [2, 3]]; Output false

Constraints

1 ≤ n ≤ 10⁵ 0 ≤ edges.length ≤ min(n·(n-1)/2, 2·10⁵) Edges are undirected and may form multiple components

Practice Detect Cycle in Undirected Graph (BFS) free on ExecCode. Browse DSA problems, topic map, and placement guides.