Couples Holding Hands (LeetCode 765): Solution and Explanation

Hard
Greedy
Depth First Search
Breadth First Search
Union Find
Graph

People numbered 0 to 2n - 1 sit in a row of seats, and the couples are (0, 1), (2, 3) and so on. A swap exchanges any two people. Find the minimum number of swaps so that every couple sits in one of the seat pairs (0, 1), (2, 3) and so on.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Seats come in fixed pairs: seats 0 and 1, seats 2 and 3, and so on. A couple is happy when both partners share one of those pairs. A useful trick for finding a partner is XOR with 1: flipping the lowest bit turns 0 into 1, 1 into 0, 2 into 3 and 3 into 2, so the partner of x is always x ^ 1.

The greedy idea is to walk the seat pairs left to right and fix each one immediately. Keep whoever sits in the left seat, and if the right seat holds someone other than their partner, swap the partner into it. Each such swap completes a couple and never breaks one already fixed, since the partner was sitting in a later, unfinished pair. It may feel like we should choose more carefully, for example deciding whether to move the left person instead, but it does not matter.

The reason comes from a graph view. Treat each seat pair as a node and draw an edge between two nodes whenever a couple is split across them. Every node has degree two, so the graph breaks into cycles. A cycle touching c seat pairs needs exactly c - 1 swaps to resolve, and each greedy swap shrinks some cycle by one pair. The total, n minus the number of cycles, is the minimum, and the greedy reaches it. To make each swap O(1), keep a pos map from person to seat so we can find the partner without scanning.

Approach: Greedy swaps with a position map

  1. Build pos, mapping each person to their current seat index.
  2. Walk the seats in steps of two, taking first = row[i] and partner = first ^ 1.
  3. If row[i + 1] is already the partner, move on.
  4. Otherwise find partnerPos = pos[partner] and swap the person at i + 1 with the partner.
  5. Update both people's entries in pos and the two seats in row, then add one to swaps.
  6. Return swaps after the last seat pair.

Step-by-step example

row = [5, 4, 2, 6, 3, 1, 0, 7]
  1. Seats 0 and 1: person 5's partner is 5 ^ 1 = 4, who is already in seat 1. No swap.
  2. Seats 2 and 3: person 2's partner is 3, but seat 3 holds 6. Person 3 is at seat 4, so swap 6 and 3. The row becomes [5, 4, 2, 3, 6, 1, 0, 7] and swaps = 1.
  3. Seats 4 and 5: person 6's partner is 7, but seat 5 holds 1. Person 7 is at seat 7, so swap 1 and 7. The row becomes [5, 4, 2, 3, 6, 7, 0, 1] and swaps = 2.
  4. Seats 6 and 7: person 0's partner 1 is already in seat 7.
  5. The answer is 2.

Code: Python, Java, C++

1class Solution:
2    def minSwapsCouples(self, row: List[int]) -> int:
3        n = len(row)
4        pos = {v: i for i, v in enumerate(row)}
5        swaps = 0
6
7        for i in range(0, n, 2):
8            first = row[i]
9            # Partner of person x is x^1 (0<->1, 2<->3, etc.)
10            partner = first ^ 1
11
12            if row[i + 1] != partner:
13                # Swap partner to position i+1
14                partnerPos = pos[partner]
15                # Swap row[i+1] with row[partnerPos]
16                pos[row[i + 1]] = partnerPos
17                pos[partner] = i + 1
18                row[partnerPos] = row[i + 1]
19                row[i + 1] = partner
20                swaps += 1
21
22        return swaps

Time and space complexity

Time

O(n)

Building the position map is linear, and each of the n / 2 seat pairs does O(1) work, including at most one swap.

Space

O(n)

The position map stores one entry per person.

Other approaches

Union-find on couples (time O(n α(n)), space O(n))

For each seat pair, union the couple IDs row[i] // 2 and row[i + 1] // 2. Each connected component of size c needs c - 1 swaps, so the answer is the number of couples minus the number of components. It makes the cycle argument explicit.

Common mistakes

  • Computing the partner as x + 1 for every person. That is wrong for odd numbers, which need x - 1, and XOR with 1 handles both cases.
  • Scanning the row for the partner on each swap instead of using the position map, which makes the algorithm O(n²).
  • Updating row but not pos after a swap, so later lookups point at stale seats.
  • Treating any two adjacent seats as a pair. Only seats (2k, 2k + 1) form a pair, so a couple sitting in seats 1 and 2 is still split.

Frequently asked questions

Why is the greedy approach optimal for Couples Holding Hands?

Couples split across seat pairs form cycles, and a cycle covering c seat pairs needs at least c - 1 swaps. Each greedy swap fixes one couple and reduces a cycle by one, so the greedy uses exactly the minimum.

How does XOR find a person's partner?

Couples are (0, 1), (2, 3) and so on, which differ only in the lowest bit. XOR with 1 flips that bit, mapping each person to their partner in both directions.

Is there a union-find solution?

Yes. Union the couple IDs that share each seat pair, then the answer is the number of couples minus the number of connected components. It gives the same result as the greedy.