Detect a cycle in an undirected graph

Graphs Cycles Hard

Given an undirected graph with V vertices labeled from 0 to V-1. The graph is represented using an adjacency list where adj[i] lists all nodes connected to node. Determine if the graph contains any cycles.

Note: The graph does not contain any self-edges (edges where a vertex is connected to itself).

Examples:


Input: V = 6, adj= [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]]

Output: True

Explanation: The graph contains a cycle: 0 ->1 -> 2 -> 5 -> 4 -> 1.

Input: V = 4, adj= [[1, 2], [0], [0, 3], [2]]

Output: False

Explanation: The graph does not contain any cycles.

Input: V = 4, adj= [[1, 2], [0, 2], [0, 1, 3], [2]]

Constraints

  • E=number of edges
  • 1 ≤ V, E ≤ 104

Hints

  • "Use DFS with a visited array to track traversal. A cycle exists if a visited node is reached again and it is not the parent node."
  • "Use Union-Find to track connected components. If an edge connects two nodes already in the same set, a cycle is detected."

Company Tags

DoorDash Databricks Shopify Intel Bloomberg Epic Games Western Digital Instacart Mastercard Johnson & Johnson Reddit Ubisoft Wayfair HashiCorp Deloitte Morgan Stanley Zynga Etsy Broadcom Boston Consulting Group Goldman Sachs Robinhood Square Electronic Arts Walmart Google Microsoft Amazon Meta Apple Netflix Adobe