TRT
Sign in
mediumAdvancedLeetCode#component counting#union-find

Number of connected components in an undirected graph

Count the connected components of a graph by starting a search from every vertex not yet visited.

The Runtime Theory Team1 min read
Taught inCycles and connected componentsPro — members onlyOne walk over a graph can split it into connected pieces, tell whether it is a tree, and find cycles. Directed graphs need one extra idea: remembering which vertices are on the current path.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 5, edges = [[0, 1], [1, 2], [3, 4]]

out2

inn = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]]

out1

inn = 3, edges = []

out3

Given n vertices and a list of undirected edges, return the number of connected components.

Before you code

Each search from an unvisited vertex marks one whole component, so the number of searches you start is the answer. Isolated vertices count as components too.

Hints

  1. Build adjacency lists.
  2. Loop over all vertices; for each unvisited one, add 1 and run BFS or DFS.
  3. Union-find solves it without adjacency lists: start with n components and subtract 1 for every edge that joins two different sets.

Production & complexity notes

When solving Number of connected components in an undirected graph on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Cycles and connected components to reinforce the underlying pattern.

What it practices

Counting components, from Cycles and connected components.

Not started

Sign in to save your learning progress.

Sign in to save