Problem 547

Abstract / Summary

Count the number of disconnected groups in a network of cities using given connections.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0547.py

class Solution:
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        size = len(isConnected)

        # union find algo
        parent = [ i for i in range(size) ]

        def union(x, y):
            parent[find(max(x, y))] = find(min(x, y))

        def find(x):
            if parent[x] != x:
                parent[x] = find(parent[x])
            return parent[x]

        for i in range(size):
            for j in range(i + 1, size):
                if isConnected[i][j] == 1:
                    union(i, j)

        # distinct parents
        distinct = set([ find(i) for i in range(size) ])
        return len(distinct)
23 lines | 675 bytes | submitted September 13, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (2+ million submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Graph Theory
  • Union Find
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of counting the number of provinces (connected components) in an undirected graph represented by an adjacency matrix isConnected. It employs a Union-Find (Disjoint Set Union) data structure to merge nodes that are directly connected and then counts the distinct root representatives to obtain the final result.

Key Steps

The algorithm can be broken down into three logical phases: initialization of the Union-Find structure, processing of the adjacency matrix to perform unions, and extraction of the distinct sets.

Initialization

A list parent is created where each node is initially its own representative.

size = len(isConnected)
parent = [i for i in range(size)]

Find Operation

The find function implements path compression. When a node’s parent is not itself, the function recursively finds the ultimate root and updates the node’s parent to point directly to that root, flattening the tree for future queries.

def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])
    return parent[x]

Union Operation

The union function merges two sets by linking the larger index to the smaller one. It first determines the roots of the two nodes using find and then makes the root with the larger index point to the root with the smaller index.

def union(x, y):
    parent[find(max(x, y))] = find(min(x, y))

Traversing the Matrix

The double loop iterates over the upper triangle of the adjacency matrix (excluding the diagonal) to avoid redundant checks, because the matrix is symmetric for an undirected graph. Whenever a 1 is encountered, indicating a direct connection, the corresponding nodes are united.

for i in range(size):
    for j in range(i + 1, size):
        if isConnected[i][j] == 1:
            union(i, j)

Counting Distinct Provinces

After all unions are performed, the algorithm computes the set of unique root representatives by applying find to each node. The cardinality of this set equals the number of provinces.

distinct = set(find(i) for i in range(size))
return len(distinct)

Edge Cases Handled

The implementation gracefully handles several boundary conditions:

  • Empty Graph - When isConnected is an empty list, size becomes 0. The loops are bypassed, distinct becomes an empty set, and the function returns 0, correctly indicating no provinces.
  • Single Node - With a 1x1 matrix containing 0 (no self-connection), the initialization creates a single parent entry. No union occurs, and the distinct set contains one element, yielding a result of 1, which matches the expectation that a solitary city forms its own province.
  • Fully Connected Graph - If every off-diagonal entry is 1, the nested loops will invoke union for every pair, ultimately collapsing all nodes under a single root. The final distinct set will contain one element, correctly reporting a single province.
  • Disconnected Subgraphs - The algorithm processes each connected component independently. Because unions are only performed when a direct edge exists, isolated clusters remain separate, and each cluster’s root persists in the final distinct set.

Performance Optimizations

Two notable optimizations are embedded in the Union-Find implementation:

  • Path Compression - The recursive find updates each visited node’s parent to the ultimate root. This reduces the depth of the tree, ensuring that subsequent find calls execute in near-constant time.
  • Upper-Triangle Traversal - By iterating only over j values greater than i, the algorithm avoids processing each edge twice. This halves the number of adjacency checks compared to a full matrix scan, cutting unnecessary work without affecting correctness.

Together, these techniques keep the algorithm efficient even for larger adjacency matrices, delivering fast convergence to the final count of provinces.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big room full of children who are holding hands in little groups. Some children are all connected in a circle, and some are just standing by themselves. This code is like a game where you go around the room to count how many separate groups of friends there are.

First, you make a list that keeps track of who is the leader of each child's group. At the beginning, every child thinks they are the leader of their own little group.

Then, you look at a special map that tells you which children are holding hands. If two children are holding hands, you join their groups together. You keep doing this for every single pair of children in the room.

To find the leaders, you check which group each child belongs to. If a child is not the leader, you follow the line of who is holding whose hand until you find the person at the very front of the line who is the leader of that whole group.

Once you have finished checking everyone, you look at all the leaders. Since every friend in a group follows the same leader, you just count how many unique leaders exist. This total number tells you exactly how many separate circles of friends are inside the room.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.27 | σ = 1.19

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
charles-wangkai Java
DimitrisJim C
everthis JS
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
39 links | 25 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

14 solutions   September 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality