Number of Provinces

Pattern: Connected components and islands

medium

Cities joined directly or through other cities form one province. The input is an adjacency matrix; start a search from every city not yet visited, and count the searches.

The problem

Given an n × n matrix where isConnected[i][j] = 1 when cities i and j are directly joined, return the number of provinces (groups of cities joined directly or indirectly).

Think first

  • What is a province in graph terms?
  • How do you read neighbours from a matrix?
  • When does a new province start?

Hints

    Brute force, and why it fails

    Union-find over every 1 in the matrix: the same O(n²).

    The key insight

    Each search from an unvisited city marks exactly one province.

    Dry run

    provinces1

    isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]. Start at 0: reach 1.

    Step 1 of 3

    The plan

    for s: if not seen: provinces += 1; search from s over the matrix row
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    Every matrix cell is read once.

    Edge cases

    • One city: 1.
    • No roads: n.
    • Everything joined: 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findCircleNum(int[][] isConnected) {
            int n = isConnected.length, provinces = 0;
            boolean[] seen = new boolean[n];
            for (int s = 0; s < n; s++) {
                if (seen[s]) continue;
                provinces++;                        // a city not reached yet starts a new province
                Deque<Integer> st = new ArrayDeque<>();
                st.push(s);
                seen[s] = true;
                while (!st.isEmpty()) {
                    int u = st.pop();
                    for (int v = 0; v < n; v++) if (isConnected[u][v] == 1 && !seen[v]) { seen[v] = true; st.push(v); }
                }
            }
            return provinces;
        }
    }

    C++

    class Solution {
    public:
        int findCircleNum(vector<vector<int>>& isConnected) {
            int n = static_cast<int>(isConnected.size()), provinces = 0;
            vector<bool> seen(n, false);
            for (int s = 0; s < n; s++) {
                if (seen[s]) continue;
                provinces++;                        // a city not reached yet starts a new province
                vector<int> st(1, s);
                seen[s] = true;
                while (!st.empty()) {
                    int u = st.back();
                    st.pop_back();
                    for (int v = 0; v < n; v++) if (isConnected[u][v] == 1 && !seen[v]) { seen[v] = true; st.push_back(v); }
                }
            }
            return provinces;
        }
    };

    Python

    class Solution:
        def findCircleNum(self, isConnected: list[list[int]]) -> int:
            n, provinces, seen = len(isConnected), 0, set()
            for s in range(n):
                if s in seen:
                    continue
                provinces += 1                      # a city not reached yet starts a new province
                seen.add(s)
                st = [s]
                while st:
                    u = st.pop()
                    for v in range(n):
                        if isConnected[u][v] and v not in seen:
                            seen.add(v)
                            st.append(v)
            return provinces

    Common mistakes

    • Counting the 1s in the matrix.
    • Forgetting that the diagonal is 1.

    Similar problems