Number of Operations to Make Network Connected — LeetCode 1319 Python Solution

MediumDepth-First SearchBreadth-First SearchUnion FindGraph
Problem
#1319
Pattern
Union-Find
Reading time
3 min

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

Python
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 - 1

Complexity

MeasureComplexity
TimeO(m \times \log n)
SpaceO(n) auxiliary

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

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 \times \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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview