Couples Holding Hands
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Couples Holding Hands
There are couples sitting in seats. Every couple is assigned IDs . Return the minimum number of swaps so that every couple is sitting side by side.
Mathematical Insight
This is a permutation decomposition problem. If we have couples and they form cycles (connected components of incorrectly paired couples), the number of swaps needed is .
Examples
Input: row = [0,2,1,3]
Output: 1
Approach 1
Level II: Greedy Swaps
Intuition
Iterate through the seats in pairs. For each seat and , if they are not already a couple, find where the partner of the person at seat is sitting and swap them into seat . This local greedy strategy is optimal.
⏱ O(N^2) for finding the partner each time.💾 O(1).
Approach 2
Level III: Union-Find (Cycle Decomposition)
Intuition
Each pair of seats should hold a couple. If seat pair holds parts of couple and couple , union and . The number of swaps is total couples minus number of components.
⏱ O(N \cdot \alpha(N)).💾 O(N).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.