TRT
Sign in
mediumAdvancedLeetCode#union-find#connected components

Number of provinces

Count the groups of cities connected directly or indirectly, given an adjacency matrix, with union-find.

The Runtime Theory Team1 min read
Taught inDisjoint setsPro — members onlyUnion-find keeps elements in groups that only ever merge. Each group is a tree of parent pointers, its root names the group, and two questions, which group is x in and merge these two groups, cover a surprising range of problems.
Solve it

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

Sample cases

inisConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]

out2

inisConnected = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

out3

inisConnected = [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 1, 1]]

out1

inisConnected = [[1]]

out1

There are n cities. isConnected[i][j] is 1 when cities i and j are directly connected. A province is a group of cities connected directly or through other cities. Return the number of provinces.

Before you code

Start with every city in its own province. What happens to the count each time a union merges two different groups, and what happens when it doesn't?

Hints

  1. The matrix is symmetric, so only look at pairs with j greater than i.
  2. Start the count at n, and subtract 1 for every union that merges two different groups.
  3. Compare with a depth-first search solution: both are O(n²) here, since reading the matrix dominates.

Production & complexity notes

When solving Number of provinces 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 Disjoint sets to reinforce the underlying pattern.

What it practices

Counting components with union-find, from Disjoint sets.

Not started

Sign in to save your learning progress.

Sign in to save