
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.
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.
1#include <stdio.h>
2#include <stdbool.h>
3
4int minSwapsCouples(int* row, int rowSize) {
5 int pos[rowSize];
6 for (int i = 0; i < rowSize; i++) {
7 pos[row[i]] = i;
8 }
9
10 int swaps = 0;
11 for (int i = 0; i < rowSize; i += 2) {
12 int partner = row[i] ^ 1;
13 if (row[i+1] != partner) {
14 swaps++;
15 int swapWith = pos[partner];
16 pos[row[i+1]] = swapWith;
17 int temp = row[i+1];
18 row[i+1] = row[swapWith];
19 row[swapWith] = temp;
20 }
21 }
22 return swaps;
23}
24
25int main() {
26 int row[] = {0, 2, 1, 3};
27 int size = sizeof(row) / sizeof(row[0]);
28 printf("Minimum swaps required: %d", minSwapsCouples(row, size));
29 return 0;
30}This C solution computes individual positions of persons to navigate swaps straightforwardly by positioning partners near one another. A systematic swap reduces cycles to achieve minimized swaps.