#1319
Number of Operations to Make Network Connected
MediumDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n α(n)) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n α(n))Space O(n)
The optimal approach uses the Union-Find (Disjoint Set Union) data structure to efficiently manage and connect components. This allows us to quickly determine how many operations are needed to connect all computers.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a Union-Find structure to manage connected components.
- 2Step 2: Iterate through the connections and union the connected computers.
- 3Step 3: Count the number of unique components and calculate the number of operations needed.
solution.py28 lines
1class UnionFind:
2 def __init__(self, size):
3 self.parent = list(range(size))
4 self.rank = [1] * size
5 def find(self, x):
6 if self.parent[x] != x:
7 self.parent[x] = self.find(self.parent[x])
8 return self.parent[x]
9 def union(self, x, y):
10 rootX = self.find(x)
11 rootY = self.find(y)
12 if rootX != rootY:
13 if self.rank[rootX] > self.rank[rootY]:
14 self.parent[rootY] = rootX
15 elif self.rank[rootX] < self.rank[rootY]:
16 self.parent[rootX] = rootY
17 else:
18 self.parent[rootY] = rootX
19 self.rank[rootX] += 1
20
21def makeConnected(n, connections):
22 if len(connections) < n - 1:
23 return -1
24 uf = UnionFind(n)
25 for a, b in connections:
26 uf.union(a, b)
27 components = len(set(uf.find(i) for i in range(n)))
28 return components - 1ℹ
Complexity note: The time complexity is nearly O(n) due to the efficient union-find operations, where α(n) is the inverse Ackermann function, which grows very slowly. The space complexity is O(n) for storing the parent and rank arrays.
- 1If the number of connections is less than n - 1, it's impossible to connect all computers.
- 2The number of operations needed to connect all computers is equal to the number of isolated components minus one.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.