Skip to problem
←

Cycle in an Undirected Graph

Easy 0 attempts

You're handed an undirected graph and need to figure out whether it has a cycle anywhere in it — a route that leaves a vertex, travels along distinct edges without reusing any of them, and eventually comes back to that same starting vertex.

The graph isn't guaranteed to be connected, so check every component. The input is V and an edge list edges; each undirected edge is listed exactly once.

Vertices are labeled 0 through V - 1. Each list entry represents one edge; do not add a second entry merely to indicate its reverse direction. Repeated endpoint pairs represent distinct parallel edges. A self-loop is a cycle, and two parallel edges form a cycle of length two. Traversing one ordinary edge out and back does not count, because that reuses the same edge.

Function contract

Implement hasCycle(V, edges).

Output: Return true if any connected component contains a cycle, otherwise false.

Example 1

Input
V = 5
edges = [[0,1],[1,2],[2,0],[3,4]]
Output
true

Example 2

Input
V = 3
edges = [[0,1],[1,2]]
Output
false
Constraints
  • 1 <= V <= 10^5
  • 0 <= edges.length <= 10^5
  • Each edge is a pair of vertex indices in [0,V-1].
  • Self-loops and parallel edges are allowed; each edge-list entry is a separate edge

Union-Find

Before adding an edge, check whether its endpoints are already connected by previously processed edges. If they are, the new edge closes a cycle. Otherwise merge their components. This naturally handles disconnected graphs, self-loops, and distinct parallel edges.

Path compression and union by size keep component lookups nearly constant amortized time.

javascript
function hasCycle(V, edges) {
  const parent = Array.from({length:V},(_,i)=>i);
  const size = Array(parent.length).fill(1);
  function find(x) { while(parent[x]!==x){parent[x]=parent[parent[x]];x=parent[x];}return x; }
  function union(a,b) { a=find(a);b=find(b);if(a===b)return;if(size[a]<size[b])[a,b]=[b,a];parent[b]=a;size[a]+=size[b]; }
  for (const [u,v] of edges) {
    if (find(u)===find(v)) return true;
    union(u,v);
  }
  return false;
}

Time: O(V + E α(V)), including initialization | Space: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript