Number of Connected Components in an Undirected Graph
Problem Statement
You have a graph with n nodes labelled 0 to n − 1. The graph is undirected: each edges[i] = [a, b] is one link between nodes a and b, and it works in both directions.
A connected component is a group of nodes where every node can reach every other node through links, and no link leaves the group.
Return the number of connected components in the graph.
n, the number of nodes, and edges, a list of [a, b] pairs.
One integer: the number of connected components.
The two components are {0, 1, 2} and {3, 4}.
The path 0 – 1 – 2 – 3 – 4 links all five nodes into one component.
No links at all, so every node is its own component.
- • Nodes are labelled 0 to n − 1.
- • Each edge is a pair [a, b] of node labels from 0 to n − 1.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Label each node with its component; an edge renames a whole component
Union every edge; each union that really merges removes one from n
Start with label[v] = v. For each edge (a, b) with different labels, rename every node that has label[b] to label[a]. At the end, the number of distinct labels is the number of components.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.