Problem Description
There are n couples sitting in 2n seats arranged in a row. Each person is represented by a unique ID, and couples are defined as (0,1), (2,3), …, (2n-2,2n-1). The task is to determine the minimum number of swaps required so that every couple is sitting side by side. A swap consists of selecting any two people and switching their seats.
Key Insights
- Treat each couple as a group; if two people sitting together are not a true couple, they belong to different groups that need connection.
- Modeling the problem using a union-find (disjoint set) structure efficiently finds connected components (cycles).
- For each connected cycle of size k (representing k couples that are interwoven), a minimum of k-1 swaps will arrange them correctly.
- Alternative approaches using DFS/BFS or a greedy strategy are also viable.
Space and Time Complexity
Time Complexity: O(n) – We iterate once over the row and union-find operations are nearly constant time. Space Complexity: O(n) – Extra space for the union-find parent array and associated mapping structures.
Solution
We solve the problem by modeling the seating arrangement as a graph where each node represents a couple. We use union-find to combine nodes (couple groups) that are incorrectly paired in the seating arrangement. For every adjacent pair in the row, if the two persons belong to different couples, their corresponding groups are merged. Finally, each connected component (cycle) requiring k-1 swaps is counted to get the total number of swaps.