|
| 1 | +package math; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 23/06/2018. |
| 5 | + * N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so |
| 6 | + * that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and |
| 7 | + * switch seats. |
| 8 | +
|
| 9 | + The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first |
| 10 | + couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). |
| 11 | +
|
| 12 | + The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th |
| 13 | + seat. |
| 14 | +
|
| 15 | + Example 1: |
| 16 | +
|
| 17 | + Input: row = [0, 2, 1, 3] |
| 18 | + Output: 1 |
| 19 | + Explanation: We only need to swap the second (row[1]) and third (row[2]) person. |
| 20 | + Example 2: |
| 21 | +
|
| 22 | + Input: row = [3, 2, 0, 1] |
| 23 | + Output: 0 |
| 24 | + Explanation: All couples are already seated side by side. |
| 25 | + Note: |
| 26 | +
|
| 27 | + len(row) is even and in the range of [4, 60]. |
| 28 | + row is guaranteed to be a permutation of 0...len(row)-1. |
| 29 | +
|
| 30 | + Solution: O(N ^ 2). Find the index i of every even-number n and (n + 1)th number. If the index i of number n is even |
| 31 | + then swap the number (n + 1) with index i + 1, else swap the number (n + 1) with index i - 1. Count the total swaps |
| 32 | + and return the answer. |
| 33 | + */ |
| 34 | +public class CouplesHoldingHands { |
| 35 | + /** |
| 36 | + * Main method |
| 37 | + * @param args |
| 38 | + * @throws Exception |
| 39 | + */ |
| 40 | + public static void main(String[] args) throws Exception{ |
| 41 | + int[] A = {1, 3, 4, 0, 2, 5}; |
| 42 | + System.out.println(new CouplesHoldingHands().minSwapsCouples(A)); |
| 43 | + } |
| 44 | + |
| 45 | + public int minSwapsCouples(int[] row) { |
| 46 | + int N = row.length; |
| 47 | + int count = 0; |
| 48 | + for(int i = 0; i < N; i +=2){ |
| 49 | + int pos = find(row, i); |
| 50 | + if((pos % 2) == 0){ |
| 51 | + if(row[pos + 1] != i + 1){ |
| 52 | + int nexNumPos = find(row, i + 1); |
| 53 | + swap(row, pos + 1, nexNumPos); |
| 54 | + count ++; |
| 55 | + } |
| 56 | + } else{ |
| 57 | + if(row[pos - 1] != i + 1){ |
| 58 | + int nexNumPos = find(row, i + 1); |
| 59 | + swap(row, pos - 1, nexNumPos); |
| 60 | + count ++; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + return count; |
| 65 | + } |
| 66 | + |
| 67 | + private int find(int[] A, int n){ |
| 68 | + for(int i = 0; i < A.length; i ++){ |
| 69 | + if(A[i] == n){ |
| 70 | + return i; |
| 71 | + } |
| 72 | + } |
| 73 | + return -1; |
| 74 | + } |
| 75 | + |
| 76 | + private void swap(int[] A, int i, int j){ |
| 77 | + int temp = A[i]; |
| 78 | + A[i] = A[j]; |
| 79 | + A[j] = temp; |
| 80 | + } |
| 81 | +} |
0 commit comments