765. Couples Holding Hands
Description
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 ith
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.
Example 1:
Input: row = [0,2,1,3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2:
Input: row = [3,2,0,1] Output: 0 Explanation: All couples are already seated side by side.
Constraints:
2n == row.length
2 <= n <= 30
n
is even.0 <= row[i] < 2n
- All the elements of
row
are unique.
Solutions
Solution 1: Union-Find
We can assign a number to each pair of couples. Person with number \(0\) and \(1\) corresponds to couple \(0\), person with number \(2\) and \(3\) corresponds to couple \(1\), and so on. In other words, the person corresponding to \(row[i]\) has a couple number of \(\lfloor \frac{row[i]}{2} \rfloor\).
If there are \(k\) pairs of couples who are seated incorrectly with respect to each other, i.e., if \(k\) pairs of couples are in the same permutation cycle, it will take \(k-1\) swaps for all of them to be seated correctly.
Why? Consider the following: we first adjust the positions of a couple to their correct seats. After this, the problem reduces from \(k\) couples to \(k-1\) couples. This process continues, and when \(k = 1\), the number of swaps required is \(0\). Therefore, if \(k\) pairs of couples are in the wrong positions, we need \(k-1\) swaps.
Thus, we only need to traverse the array once, use union-find to determine how many permutation cycles there are. Suppose there are \(x\) cycles, and the size of each cycle (in terms of couple pairs) is \(y_1, y_2, \cdots, y_x\). The number of swaps required is \(y_1-1 + y_2-1 + \cdots + y_x-1 = y_1 + y_2 + \cdots + y_x - x = n - x\).
The time complexity is \(O(n \times \alpha(n))\), and the space complexity is \(O(n)\), where \(\alpha(n)\) is the inverse Ackermann function, which can be considered a very small constant.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|