Number of Provinces

Union-find over the friendship matrix — count distinct roots.

Medium
Time O(n^2 * alpha(n)) Space O(n)
LeetCode
4 min read
union-find graph matrix

Problem#

isConnected[i][j] = 1 iff city i and city j are directly connected. Return the number of provinces (connected components).

Examples#

  • [[1,1,0],[1,1,0],[0,0,1]]2.
  • [[1,0,0],[0,1,0],[0,0,1]]3.

Constraints#

  • 1 <= n <= 200.

Approach#

Union-find. Iterate the upper triangle of the matrix; union any pair connected. Return the count of components.

Solution#

Number of Provinces
class Solution {
vector<int> par;
int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); }
public:
int findCircleNum(vector<vector<int>>& g) {
int n = g.size();
par.resize(n);
iota(par.begin(), par.end(), 0);
int comps = n;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
if (g[i][j]) {
int a = find(i), b = find(j);
if (a != b) { par[a] = b; --comps; }
}
return comps;
}
};

Editorial#

DSU is the cleanest tool for this — DFS over the adjacency matrix also works in the same O(n^2). We only need the upper triangle since the matrix is symmetric.

Complexity#

  • Time: ~O(n^2).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.