Couples Holding Hands - Problem
There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the i-th seat.
The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).
Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
Input & Output
Example 1 — Basic Mixed Couples
$
Input:
row = [0,2,1,3]
›
Output:
1
💡 Note:
Couples are (0,1) and (2,3). Currently seated as (0,2) and (1,3). Swap positions 1 and 2 to get [0,1,2,3] where couples sit together.
Example 2 — Already Correct
$
Input:
row = [3,2,0,1]
›
Output:
0
💡 Note:
Couples (2,3) and (0,1) are already sitting together in pairs, just in different order. No swaps needed.
Example 3 — Complex Mixing
$
Input:
row = [1,4,2,3,5,0]
›
Output:
2
💡 Note:
Three couples (0,1), (2,3), (4,5) are mixed. Need 2 swaps: swap 4 with 0 to get [1,0,2,3,5,4], then couples sit together.
Constraints
- 2 ≤ row.length ≤ 60
- row.length is even
- 0 ≤ row[i] < row.length
-
All elements of
roware unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
People sitting with wrong partners: [0,2,1,3]
2
Process
Identify mixed couples and perform minimum swaps
3
Output
Return minimum number of swaps needed: 1
Key Takeaway
🎯 Key Insight: Use greedy approach - fix each misplaced couple immediately when found
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code