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)
Difficulty
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
AI Disclaimer
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.
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
isConnectedis an empty list,sizebecomes0. The loops are bypassed,distinctbecomes an empty set, and the function returns0, correctly indicating no provinces. - Single Node - With a
1x1matrix containing0(no self-connection), the initialization creates a single parent entry. No union occurs, and the distinct set contains one element, yielding a result of1, 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 invokeunionfor 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
findupdates each visited node’s parent to the ultimate root. This reduces the depth of the tree, ensuring that subsequentfindcalls execute in near-constant time. - Upper-Triangle Traversal - By iterating only over
jvalues greater thani, 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 323: Number of Connected Components in an Undirected Graph
- problem 657: Robot Return to Origin
- problem 734: Sentence Similarity
- problem 737: Sentence Similarity II
- problem 1101: The Earliest Moment When Everyone Become Friends
- problem 2101: Detonate the Maximum Bombs
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 557: Reverse Words in a String III
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 819: Most Common Word
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 399: Evaluate Division
- problem 435: Non-overlapping Intervals
- problem 841: Keys and Rooms
- problem 1466: Reorder Routes to Make All Paths Lead to the City Zero
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
Extra
- 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