Sponsored
Sponsored
This approach uses a Union-Find (also known as Disjoint Set Union, DSU) data structure to count the number of swaps needed to pair the couples. By treating each couple as a connected component, we can iterate through the row and connect each person to their designated partner. The number of swaps needed is equivalent to the number of components minus one.
Time Complexity: O(N), where N is the number of seats, because each union-find operation is O(1) on average using path compression and union by rank.
Space Complexity: O(N) for the parent array to store the parent of each node.
1class UnionFind:
2 def __init__(self, n):
3 self.parent = list(range(n))
4
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
10 def union(self, x, y):
11 rootX = self.find(x)
12 rootY = self.find(y)
13 if rootX != rootY:
14 self.parent[rootX] = rootY
15
16class Solution:
17 def minSwapsCouples(self, row):
18 n = len(row) // 2
19 uf = UnionFind(n)
20 for i in range(0, len(row), 2):
21 a, b = row[i] // 2, row[i + 1] // 2
22 uf.union(a, b)
23
24 return sum(1 for i in range(n) if uf.find(i) == i) - 1
25
26row = [0, 2, 1, 3]
27sol = Solution()
28print(f"Minimum swaps required: {sol.minSwapsCouples(row)}")
The Python solution applies Union-Find to group together people who should be seated as couples. By finding the number of disjoint sets after processing the union operations, it derives the minimum number of swaps required to correctly seat all couples side by side.
This approach processes the row greedily to minimize swaps by placing each person in its correct position. Misplaced pairs turn into cycles; reducing each cycle requires one swap for each element in excess of two in the cycle. Thus, we can directly count cycles and deduce swaps.
Time Complexity: O(N), iterating the seats for correction.
Space Complexity: O(N), necessary to track positions of individuals.
1using System.Collections.Generic;
public class Solution {
public int MinSwapsCouples(int[] row) {
int n = row.Length;
int[] pos = new int[n];
for (int i = 0; i < n; i++) {
pos[row[i]] = i;
}
int swaps = 0;
for (int i = 0; i < n; i += 2) {
int partner = row[i] ^ 1;
if (row[i + 1] != partner) {
swaps++;
int swapWith = pos[partner];
pos[row[i + 1]] = swapWith;
int temp = row[i + 1];
row[i + 1] = row[swapWith];
row[swapWith] = temp;
}
}
return swaps;
}
public static void Main(string[] args) {
int[] row = {0, 2, 1, 3};
Solution sol = new Solution();
Console.WriteLine("Minimum swaps required: " + sol.MinSwapsCouples(row));
}
}
This C# solution iterates over the row, evaluating partner relationships through mathematical partners indices, and reorders using direct swaps, delivering a correct number of operations needed.