Detect Cycle in Undirected Graph (DFS) Problem

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

Solve the Detect Cycle in Undirected Graph (DFS) 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 DFS and pass the parent so the edge back to the caller is ignored.

Examples

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

Constraints

1 ≤ n ≤ 10⁵ 0 ≤ edges.length ≤ min(n·(n-1)/2, 2·10⁵) Graph may be disconnected

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