#765
Couples Holding Hands
HardGreedyDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryUnion-FindGraph Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a greedy approach with a Union-Find data structure to efficiently group couples and count the minimum swaps needed. This is much faster than brute force because it avoids unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a Union-Find structure to represent the couples.
- 2Step 2: Iterate through the row and union each person with their partner based on their indices.
- 3Step 3: Count the number of unique groups formed and calculate the number of swaps needed based on the number of groups.
solution.py18 lines
1class UnionFind:
2 def __init__(self, n):
3 self.parent = list(range(n))
4 def find(self, x):
5 if self.parent[x] != x:
6 self.parent[x] = self.find(self.parent[x])
7 return self.parent[x]
8 def union(self, x, y):
9 self.parent[self.find(x)] = self.find(y)
10
11def minSwapsCouples(row):
12 n = len(row) // 2
13 uf = UnionFind(n)
14 for i in range(len(row)):
15 partner = row[i] // 2
16 uf.union(i // 2, partner)
17 groups = len(set(uf.find(i) for i in range(n)))
18 return n - groupsℹ
Complexity note: The time complexity is O(n) because we perform a constant amount of work for each person in the row, and the space complexity is O(n) due to the Union-Find structure.
- 1Couples can be represented as pairs, and finding swaps can be thought of as connecting nodes in a graph.
- 2Using Union-Find allows us to efficiently manage and group connected components.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.