MediumNo. 1319
Number of Operations to Make Network Connected — LeetCode 1319 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Graph
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Example
- Input
- n = 4, connections = [[0,1],[0,2],[1,2]]
- Output
- 1
- Explanation
- Remove cable between computer 1 and 2 and place between computers 1 and 3.
Python solution
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
cnt = 0
p = list(range(n))
for a, b in connections:
pa, pb = find(a), find(b)
if pa == pb:
cnt += 1
else:
p[pa] = pb
n -= 1
return -1 if n - 1 > cnt else n - 1Complexity
- Time
- O(m × log n)
- Space · auxiliary
- O(n)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1319. Number of Operations to Make Network Connected 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 |
| 0547 | Number of Provinces | Medium |
| 0684 | Redundant Connection | Medium |
| 0685 | Redundant Connection II | Hard |
| 0785 | Is Graph Bipartite? | Medium |
| 0886 | Possible Bipartition | Medium |
Frequently asked questions
- How hard is LeetCode 1319. Number of Operations to Make Network Connected?
LeetCode 1319. Number of Operations to Make Network Connected is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1319. Number of Operations to Make Network Connected?
The Python solution on this page runs in O(m × log n).
- What is the space complexity of LeetCode 1319. Number of Operations to Make Network Connected?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1319. Number of Operations to Make Network Connected cover?
LeetCode 1319. Number of Operations to Make Network Connected is tagged Depth-First Search, Breadth-First Search, Union Find and Graph on LeetCode.