Skip to content
Problem 765 · LeetCode 765(opens in a new tab)

Couples Holding Hands

HardGraphs

There are n couples sitting in a row of 2n seats. row[i] is the person in seat i. People are numbered so that each couple is a pair of neighbouring numbers: 0 and 1, 2 and 3, up to 2n − 2 and 2n − 1.

Seats are paired into couches: seats 0 and 1, seats 2 and 3, and so on. In one swap, any two people trade seats. Return the fewest swaps needed so that every couch holds a couple.

Example 1

Input:  row = [4, 1, 3, 0, 5, 2]
Output: 2
Why:    swap 1 with 5, then 0 with 2
2 more examples and the constraints

Example 2

Input:  row = [2, 3, 1, 0]
Output: 0
Why:    both couches already hold a couple

Example 3

Input:  row = [5, 4, 0, 3, 2, 1]
Output: 1
Why:    swap 3 with 1

Constraints

  • 2 ≤ n ≤ 30, so row has 2n entries
  • row holds each number from 0 to 2n − 1 exactly once

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Greedy, scan for the partnerO(n²)
  2. Union-Find on couplesO(n·α(n))
  3. Greedy with a seat lookupO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30 couplesVerdict
Greedy, scan for the partnerO(n²)
Simple; fine at n = 30
Union-Find on couplesO(n·α(n))
Proves the count
Greedy with a seat lookupO(n)
Best; one pass

n = number of couples; α is the very slow-growing inverse Ackermann function.

Edge cases to test

  • Already seated. [2, 3, 1, 0] needs 0 swaps; a couple may sit in either order.
  • One long cycle. [1, 2, 3, 4, ..., 59, 0] ties all 30 couples into one cycle: 29 swaps.
  • Several small cycles. [0, 2, 1, 3, 4, 6, 5, 7] has two cycles of 2 couples: 2 swaps.
  • Partner in the last seat. The scan or lookup must reach the end of the row.

Common mistakes

  • Pairing person p with p + 1 for every p, so 1 is wrongly paired with 2. Use p ^ 1.
  • Forgetting to update the seat lookup after a swap, so later lookups point to the wrong seat.
  • Counting couples that are out of place instead of swaps; a cycle of k couples needs k − 1.

How to talk through it

  1. 1Clarify. Are seats paired as 0-1, 2-3, ...? Can a couple sit in either order? Can any two people swap?
  2. 2Give the greedy. Fix each couch left to right by swapping the partner in; scanning makes it O(n²).
  3. 3Argue it is optimal. Couples linked by shared couches form cycles; k couples in a cycle need k − 1 swaps.
  4. 4Code the lookup. Keep pos[person] so each partner is found in O(1), and update it after every swap.
  5. 5Test out loud. Run an already seated row and one long cycle before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?