Number of Provinces

MediumGraphs · Union Find🧩 Union-FindLeetCode #547 ↗Updated

Problem

There are n cities and a symmetric adjacency matrix isConnected, where isConnected[i][j] = 1 means cities i and j are directly linked. Cities linked directly or through other cities form one province. Return how many provinces there are.
Input[[1,1,0],[1,1,0],[0,0,1]]Output2
Input[[1,0,0],[0,1,0],[0,0,1]]Output3

1 ≤ n ≤ 200  ·  isConnected[i][j] ∈ {0,1}  ·  isConnected[i][i] = 1  ·  symmetric

Try it yourself

Java
class Solution {
    public int findCircleNum(int[][] isConnected) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A province is a connected component. Either flood-fill each unvisited city (each fill = one province) or start with n singleton sets and decrement the count on every union that merges two different sets.
PatternUnion-Find

Instinct Items get grouped by "connected", "same as" or "shares a" links and you keep asking which group something is in: merge sets with Union-Find.

Memory hack Find your boss, merge the bosses; squash the chain (path compression) and hang the short tree under the tall one (rank).

Open the Union-Find guide →

Approaches

Brute ForceTransitive Closure (Floyd–Warshall)

Time O(n3)Space O(n2)

Compute full reachability: i reaches j if it reaches some k that reaches j. Then count the cities that are the smallest index of their province (no smaller city reaches them).

Java
public int findCircleNum(int[][] isConnected) {
    int n = isConnected.length;
    boolean[][] reach = new boolean[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) reach[i][j] = isConnected[i][j] == 1;
    for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            if (reach[i][k])
                for (int j = 0; j < n; j++) if (reach[k][j]) reach[i][j] = true;
    int provinces = 0;
    for (int i = 0; i < n; i++) {
        boolean first = true; // i is the smallest city of its province
        for (int j = 0; j < i; j++) if (reach[j][i]) { first = false; break; }
        if (first) provinces++;
    }
    return provinces;
}

Answers every reachability query, but cubic time is overkill for a count.

At a glance

LevelApproachTimeSpace
Brute ForceTransitive Closure (Floyd–Warshall)O(n3)O(n2)
BetterDFS Flood FillO(n2)O(n)
OptimalUnion-Find (Rank + Path Compression)O(n2·α(n))O(n)
Common pitfalls
  • Counting direct links instead of components — friends of friends count.
  • Decrementing on every edge, not only on a successful merge.
  • Treating the input as an edge list — it is an n×n matrix.
Interview tips
  • Say “count connected components” — then pick DFS or Union-Find.
  • Explain why both are O(n2): the matrix itself has n2 cells.
  • Mention Union-Find shines when edges arrive dynamically.
Pattern
Union-Find / connected components → grouping items by transitive “is connected to” relations.
My notes saved in this browser