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 - Greedy Approach INPUT 2n seats in a row (n=2 couples) Seat 0 0 Seat 1 2 Seat 2 1 Seat 3 3 row = [0, 2, 1, 3] Couples: Couple 1: (0, 1) Couple 2: (2, 3) Person 0 and 1 not together! Person 2 and 3 not together! ALGORITHM STEPS 1 Check seat pair (0,1) Person 0 needs partner 1 But seat 1 has person 2 2 Find person 1's position Person 1 is at seat 2 3 Swap persons Swap person 2 and 1 2 <--> 1 4 Check remaining pairs Pair (2,3): has 2 and 3 Already a couple - OK Total Swaps: 1 FINAL RESULT After 1 swap: Seat 0 0 Seat 1 1 Seat 2 2 Seat 3 3 Couple 1 - OK Couple 2 - OK row = [0, 1, 2, 3] Output: 1 (minimum swaps) All couples holding hands! Key Insight: For couples (0,1), (2,3), ..., person X's partner is X XOR 1 (flipping the last bit). The greedy approach works because fixing one couple never breaks another already-fixed couple. Time Complexity: O(n) | Space Complexity: O(n) for position tracking TutorialsPoint - Couples Holding Hands | Greedy Approach
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