Detect a Cycle in an Undirected Graph

medium

Given an undirected graph with V vertices (0 .. V-1) and an edge list edges (no self-loops or duplicate edges), return true if it contains a cycle and false otherwise.

Hints

In an undirected graph, an edge to an already-visited vertex (other than your parent) closes a cycle.
Track the parent so the edge you arrived on isn't mistaken for a cycle.
Union-Find alternative: an edge whose endpoints are already in the same set forms a cycle.

Common doubts

Every vertex has an edge back to its parent; without excluding it, that edge would falsely look like a cycle.
If both endpoints of an edge are already connected, adding the edge creates a second path between them — a cycle.
Yes — same parent-tracking idea; just watch out for recursion depth on large graphs.

Interview follow-ups

The parent trick fails; use a recursion stack (back edge) or Kahn's algorithm.
Track parents and, on detecting a cycle, walk back from both endpoints to their meeting point.

Fun facts

  • A connected undirected graph is a tree iff it has exactly V-1 edges and no cycle.
  • Union-Find's cycle check is the core of Kruskal's MST algorithm.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 3, edges = [[0,1],[1,2],[2,0]]
Output: true
The three edges form a triangle.
Example 2
Input: V = 4, edges = [[0,1],[1,2],[2,3]]
Output: false
A path has no cycle.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - no self-loops or duplicate edges

Solve this problem →