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.
1using System;
2
3public class UnionFind {
4 private int[] parent;
5
6 public UnionFind(int size) {
7 parent = new int[size];
8 for (int i = 0; i < size; i++) {
9 parent[i] = i;
10 }
11 }
12
13 public int Find(int x) {
14 if (parent[x] != x) {
15 parent[x] = Find(parent[x]);
16 }
17 return parent[x];
18 }
19
20 public void Union(int x, int y) {
21 int rootX = Find(x);
22 int rootY = Find(y);
23 if (rootX != rootY) {
24 parent[rootX] = rootY;
25 }
26 }
27}
28
29public class Solution {
30 public int MinSwapsCouples(int[] row) {
31 int n = row.Length / 2;
32 UnionFind uf = new UnionFind(n);
33
34 for (int i = 0; i < row.Length; i += 2) {
35 int a = row[i] / 2, b = row[i + 1] / 2;
36 uf.Union(a, b);
37 }
38
39 int swaps = 0;
40 for (int i = 0; i < n; i++) {
41 if (uf.Find(i) == i) swaps++;
42 }
43
44 return swaps - 1;
45 }
46
47 public static void Main(string[] args) {
48 Solution sol = new Solution();
49 int[] row = {0, 2, 1, 3};
50 Console.WriteLine("Minimum swaps required: " + sol.MinSwapsCouples(row));
51 }
52}
The C# solution employs a Union-Find class to connect each couple's members. It iterates over the row to unite identified couples, then calculates and returns the minimum swaps necessary by checking the roots of each element in the union-find structure.
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.
1
The Python solution employs a hash table for position tracking, which pairs each individual optimally, performing swaps with their partners through logical exercises to reduce misplaced seats.