sagelearnai

Number of Provinces

Difficulty: Medium · Pattern: Union-Find · LeetCode #547

There are n cities. isConnected[i][j] = 1 if cities i and j are directly connected (the matrix is symmetric, and isConnected[i][i] = 1). Connectivity is transitive. A province is a maximal group of connected cities. Return the number of provinces.

Examples

text
[[1,1,0],
 [1,1,0],
 [0,0,1]]   →  2

[[1,0,0],
 [0,1,0],
 [0,0,1]]   →  3

Hints

  1. Start with n separate groups. Every union of two different groups reduces the count by one.
  2. Only the upper triangle of the matrix needs scanning.

Approach

Initialize a DSU with n components. For each pair i < j with isConnected[i][j] == 1, union them; if the union merged two different sets, decrement the component count. The final count is the number of provinces. DFS over the adjacency matrix is an equally good answer.

Complexity

Time: O(n²·α(n)). Space: O(n).

Python solution
def findCircleNum(isConnected):
    n = len(isConnected)
    parent = list(range(n))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    components = n
    for i in range(n):
        for j in range(i + 1, n):
            if isConnected[i][j]:
                ri, rj = find(i), find(j)
                if ri != rj:
                    parent[ri] = rj
                    components -= 1
    return components
JavaScript solution
function findCircleNum(isConnected) {
  const n = isConnected.length, parent = Array.from({ length: n }, (_, i) => i);
  const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
  let components = n;
  for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
    if (isConnected[i][j]) { const ri = find(i), rj = find(j); if (ri !== rj) { parent[ri] = rj; components--; } }
  }
  return components;
}