MediumNo. 0547
Number of Provinces — LeetCode 547 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Graph
- On a study list
- LeetCode 75
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There are n cities. Some of them are connected, while some are not.
Example
- Input
- isConnected = [[1,1,0],[1,1,0],[0,0,1]]
- Output
- 2
Python solution
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
def dfs(i: int):
vis[i] = True
for j, x in enumerate(isConnected[i]):
if not vis[j] and x:
dfs(j)
n = len(isConnected)
vis = [False] * n
ans = 0
for i in range(n):
if not vis[i]:
dfs(i)
ans += 1
return ansComplexity
- Time
- O(n2)
- Space · auxiliary
- O(n)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 547. Number of Provinces is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0399 | Evaluate Division | Medium |
| 0684 | Redundant Connection | Medium |
| 0685 | Redundant Connection II | Hard |
| 0785 | Is Graph Bipartite? | Medium |
| 0886 | Possible Bipartition | Medium |
| 1319 | Number of Operations to Make Network Connected | Medium |
Frequently asked questions
- How hard is LeetCode 547. Number of Provinces?
LeetCode 547. Number of Provinces is rated Medium on LeetCode.
- What is the time complexity of LeetCode 547. Number of Provinces?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 547. Number of Provinces?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 547. Number of Provinces cover?
LeetCode 547. Number of Provinces is tagged Depth-First Search, Breadth-First Search, Union Find and Graph on LeetCode.