Detect a cycle in an undirected graph

Graphs Cycles Hard
  • Fact: Detecting cycles in a graph is a fundamental problem that has a wide array of applications in the software industry
  • It is used in networking and telecommunication for finding routing loops or cyclical data dependencies
  • Also, it finds usage in DevOps for spotting potential infinite loops in tasks automation like ansible, puppet, etc
  • More so, in social networking applications like Facebook or LinkedIn, it can help track circular friend requests or connections
  • Algorithms for detecting cycles are extensively used in garbage collection mechanism in programming languages like Python, Java and Javascript to identify and clean up objects that are no longer needed by the program to efficiently manage memory

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