Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Graphs Medium frequency Solution Available Practice Mode

Number of Connected Components in Undirected Graph LeetCode Solution

Tags: #Graph #DFS #Union Find

Approach Summary

DFS/BFS to mark connected nodes, or Union-Find to merge edges. Count distinct components.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Graphs Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Graphs pattern.

Framework: Graphs • Interview Prep: Tested at FAANG • Explore all Graphs problems & invariants →

How to Recognize This Pattern

  • Count connected components in undirected graph

Complexity Analysis

Time Complexity

O(V + E)

Space Complexity

O(V)

Tags

Graph DFS Union Find

Frequently Asked Questions

What is the optimal time and space complexity for Number of Connected Components in Undirected Graph?
The optimal solution for Number of Connected Components in Undirected Graph achieves O(V + E) runtime complexity and requires O(V) auxiliary space. Time Complexity is O(V + E) for BFS / DFS, where V is the number of vertices and E is the number of edges, as each vertex and edge is examined at most twice. For Union-Find with path compression and union by rank, the time is O(V + E * alpha(V)) where alpha is the inverse Ackermann function (effectively constant). Space Complexity is O(V + E) to store the adjacency representation or O(V) for the visited array / parent array.
How do I identify that Number of Connected Components in Undirected Graph requires the Graphs pattern?
In technical interviews, look for key problem signals: Count connected components in undirected graph. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Graphs strategy.
What critical edge cases must be handled in Number of Connected Components in Undirected Graph?
Essential edge cases to verify include: Isolated vertices with no edges — each counts as its own component of size 1 (total components = n); Fully connected graph (clique or single spanning tree) — exactly 1 component; Empty edge list — exactly n components; Self-loops or parallel duplicate edges — handled cleanly without affecting component counts. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Number of Connected Components in Undirected Graph?
Number of Connected Components in Undirected Graph is a Medium-difficulty question tagged with medium recurrence. It is actively asked in technical screening and onsite interview loops at LinkedIn, Google, Amazon.
Buy me a coffee
Daily Practice
0/0