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 row are unique

Visualization

Tap to expand
Couples Holding Hands ProblemInput: Mixed Couples0213Person 0Person 2Person 1Person 3Not a couple!Not a couple!SWAPOutput: Fixed Arrangement0123Couple (0,1) ✓Couple (2,3) ✓1 Swap Needed
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
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
89.2K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen