MediumDepth-First SearchBreadth-First SearchUnion FindGraph

Connected Components in Undirected Graph

LeetCode
1 approach, code in all languages

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 <= 2000
  • 0 <= edges.length <= n * (n - 1) / 2
  • edges[i].length == 2
  • 0 <= a_i, b_i < n
  • a_i != b_i
  • There are no repeated edges.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now