You are given an integer n, representing an undirected graph with nodes labeled from 0 to n - 1, together with a list of undirected edges. Each entry edges[i] = [a, b] means there is an edge connecting node a and node b.
A connected component is a maximal set of nodes such that any two of them are reachable from one another through the edges. Return the total number of connected components in the graph.
Isolated nodes with no incident edges each count as their own component.
Example 1
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Nodes 0, 1, and 2 are linked into one component, and nodes 3 and 4 form another, so there are 2 components.
Example 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Every node is chained together into a single component.
Constraints
1 <= n <= 20000 <= edges.length <= n * (n - 1) / 2edges[i].length == 20 <= a_i, b_i < na_i != b_iThere are no repeated edges.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI