Connected Components

35 min · countComponents()

Imagine a company chat where some coworkers can reach each other through chains of introductions, while other groups remain completely separate. How many groups are there?

You're given n nodes labeled from 0 through n - 1. Each pair [a, b] is an undirected edge, so the connection works in both directions. Return the number of connected components — separate groups where every node can reach every other node, and no edge reaches a node outside the group.

A node with no edges forms a component by itself. Loops don't create extra components; they only add more routes inside an existing one.

Constraints

  • 1 <= n <= 2_000
  • 0 <= edges.length <= 5_000
  • Every edge contains two node labels in the range 0..n - 1.
  • There are no self-loops and no duplicate undirected edges.

Hints

One search, one group

Start from an unseen node and visit everything reachable from it. That entire walk discovers exactly one connected component.

Don't lose the loners

Iterate over all n node labels, not just labels that appear in edges. An isolated node still increases the answer.

Count successful merges

Union-find starts with n separate groups. Reduce the count only when an edge joins two roots that were previously different.

Follow-up

If new edges keep arriving, can you report the component count after each one without traversing the whole graph again?

Visible cases

Examples

Example 1

ready
Input
n = 5
edges = [
  [
    0,
    1
  ],
  [
    1,
    2
  ],
  [
    3,
    4
  ]
]
Expected
2
Why
0-1-2 form one group; 3-4 form the other

Example 2

ready
Input
n = 5
edges = [
  [
    0,
    1
  ],
  [
    1,
    2
  ],
  [
    2,
    3
  ],
  [
    3,
    4
  ]
]
Expected
1
Why
the chain reaches all five nodes

Example 3

ready
Input
n = 4
edges = []
Expected
4
Why
without edges, every node stands alone

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite