Minimum number of swaps required for arranging pairs adjacent to each other - GeeksforGeeks
https://github.com/mission-peace/interview/blob/master/src/com/interview/recursion/SetPairTogether.java
Time complexity is O(2^n)
public int findMinimumSwaps(int input[], Map<Integer, Integer> pair) {
Map<Integer, Integer> index = new HashMap<>();
for (int i = 0; i < input.length; i++) {
index.put(input[i], i);
}
return findMinimumSwapsUtil(input, pair, index, 0);
}
public int findMinimumSwapsUtil(int input[], Map<Integer, Integer> pair, Map<Integer, Integer> index, int current) {
if (current == input.length) {
return 0;
}
int v1 = input[current];
int v2 = input[current + 1];
int pv2 = pair.get(v1);
if(pv2 == v2) {
return findMinimumSwapsUtil(input, pair, index, current + 2);
} else {
int idx1 = index.get(v1);
int idx2 = index.get(v2);
int idx3 = index.get(pair.get(v1));
int idx4 = index.get(pair.get(v2));
swap(index, input, idx2, idx3);
int val1 = findMinimumSwapsUtil(input, pair, index, current + 2);
swap(index, input, idx2, idx3);
swap(index, input, idx1, idx4);
int val2 = findMinimumSwapsUtil(input, pair, index, current + 2);
swap(index, input, idx1, idx4);
return 1 + Math.min(val1, val2);
}
}
private void swap(Map<Integer, Integer> index, int input[], int i, int j) {
index.compute(input[i], (k, v) -> j);
index.compute(input[j], (k, v) -> i);
int t = input[i];
input[i] = input[j];
input[j] = t;
}
https://discuss.leetcode.com/topic/113/minimum-number-of-swaps-required-for-arranging-pairs-adjacent-to-each-other
TODO ------ not sure about its correctness
There are n-pairs and therefore 2n people. everyone has one unique number ranging from 1 to 2n. All these 2n persons are arranged in random fashion in an Array of size 2n. We are also given who is partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs become adjacent to each other.
Example:
Input: n = 3 pairs[] = {1->3, 2->6, 4->5} // 1 is partner of 3 and so on arr[] = {3, 5, 6, 4, 1, 2} Output: 2 We can get {3, 1, 5, 4, 6, 2} by swapping 5 & 6, and 6 & 1
1) If first and second elements are pair, then simply recur for remaining n-1 pairs and return the value returned by recursive call. 2) If first and second are NOT pair, then there are two ways to arrange. So try both of them return the minimum of two. a) Swap second with pair of first and recur for n-1 elements. Let the value returned by recursive call be 'a'. b) Revert the changes made by previous step. c) Swap first with pair of second and recur for n-1 elements. Let the value returned by recursive call be 'b'. d) Revert the changes made by previous step before returning control to parent call. e) Return 1 + min(a, b)
// This function updates indexes of elements 'a' and 'b'
void
updateindex(
int
index[],
int
a,
int
ai,
int
b,
int
bi)
{
index[a] = ai;
index[b] = bi;
}
// This function returns minimum number of swaps required to arrange
// all elements of arr[i..n] become aranged
int
minSwapsUtil(
int
arr[],
int
pairs[],
int
index[],
int
i,
int
n)
{
// If all pairs procesed so no swapping needed return 0
if
(i > n)
return
0;
// If current pair is valid so DO NOT DISTURB this pair
// and move ahead.
if
(pairs[arr[i]] == arr[i+1])
return
minSwapsUtil(arr, pairs, index, i+2, n);
// If we reach here, then arr[i] and arr[i+1] don't form a pair
// Swap pair of arr[i] with arr[i+1] and recursively compute
// minimum swap required if this move is made.
int
one = arr[i+1];
int
indextwo = i+1;
int
indexone = index[pairs[arr[i]]];
int
two = arr[index[pairs[arr[i]]]];
swap(arr[i+1], arr[indexone]);
updateindex(index, one, indexone, two, indextwo);
int
a = minSwapsUtil(arr, pairs, index, i+2, n);
// Backtrack to previous configuration. Also restore the
// previous indices, of one and two
swap(arr[i+1], arr[indexone]);
updateindex(index, one, indextwo, two, indexone);
one = arr[i], indexone = index[pairs[arr[i+1]]];
// Now swap arr[i] with pair of arr[i+1] and recursively
// compute minimum swaps required for the subproblem
// after this move
two = arr[index[pairs[arr[i+1]]]], indextwo = i;
swap(arr[i], arr[indexone]);
updateindex(index, one, indexone, two, indextwo);
int
b = minSwapsUtil(arr, pairs, index, i+2, n);
// Backtrack to previous configuration. Also restore
// the previous indices, of one and two
swap(arr[i], arr[indexone]);
updateindex(index, one, indextwo, two, indexone);
// Return minimum of two cases
return
1 + min(a, b);
}
// Returns minimum swaps required
int
minSwaps(
int
n,
int
pairs[],
int
arr[])
{
int
index[2*n + 1];
// To store indices of array elements
// Store index of each element in array index
for
(
int
i = 1; i <= 2*n; i++)
index[arr[i]] = i;
// Call the recursive function
return
minSwapsUtil(arr, pairs, index, 1, 2*n);
}
Time complexity is O(2^n)
public int findMinimumSwaps(int input[], Map<Integer, Integer> pair) {
Map<Integer, Integer> index = new HashMap<>();
for (int i = 0; i < input.length; i++) {
index.put(input[i], i);
}
return findMinimumSwapsUtil(input, pair, index, 0);
}
public int findMinimumSwapsUtil(int input[], Map<Integer, Integer> pair, Map<Integer, Integer> index, int current) {
if (current == input.length) {
return 0;
}
int v1 = input[current];
int v2 = input[current + 1];
int pv2 = pair.get(v1);
if(pv2 == v2) {
return findMinimumSwapsUtil(input, pair, index, current + 2);
} else {
int idx1 = index.get(v1);
int idx2 = index.get(v2);
int idx3 = index.get(pair.get(v1));
int idx4 = index.get(pair.get(v2));
swap(index, input, idx2, idx3);
int val1 = findMinimumSwapsUtil(input, pair, index, current + 2);
swap(index, input, idx2, idx3);
swap(index, input, idx1, idx4);
int val2 = findMinimumSwapsUtil(input, pair, index, current + 2);
swap(index, input, idx1, idx4);
return 1 + Math.min(val1, val2);
}
}
private void swap(Map<Integer, Integer> index, int input[], int i, int j) {
index.compute(input[i], (k, v) -> j);
index.compute(input[j], (k, v) -> i);
int t = input[i];
input[i] = input[j];
input[j] = t;
}
https://discuss.leetcode.com/topic/113/minimum-number-of-swaps-required-for-arranging-pairs-adjacent-to-each-other
This looks like another DFS problem.
There are two choices for each recursion the two numbers are not a pair.
(1) swap the second one with the first number's pair, or
(2) swap the first one with the second number's pair.
To prevent from finding the number and their pairs from the array which costs O(2n), the indexes and pairs are stored using two HashMap. Therefore, after swapping the numbers, the index map needs to be adjusted as well.
There are two choices for each recursion the two numbers are not a pair.
(1) swap the second one with the first number's pair, or
(2) swap the first one with the second number's pair.
To prevent from finding the number and their pairs from the array which costs O(2n), the indexes and pairs are stored using two HashMap. Therefore, after swapping the numbers, the index map needs to be adjusted as well.
Map<Integer, Integer> pairs = new HashMap();
Map<Integer, Integer> indexs = new HashMap();
private void swap(int[] nums, int x, int y){
int temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
private int DFS(int s, int len, int[] nums) {
if ( s >= len ) return 0;
int ret = Integer.MAX_VALUE;
int num0 = nums[s], num1 = nums[s+1];
int p0 = pairs.get(num0), p1 = pairs.get(num1);
int p0_i = indexs.get(p0), p1_i = indexs.get(p1);
if ( (num1 == p0) || (num0 == p1) ) return DFS(s+2, len, nums);
swap(nums, s+1, p0_i);
indexs.put(num1, p0_i);
indexs.put(p0, s+1);
ret = Math.min(ret, DFS(s+2, len, nums) );
swap(nums, s+1, p0_i);
indexs.put(num1, s+1);
indexs.put(p0, p0_i);
swap(nums, s, p1_i);
indexs.put(num0, p1_i);
indexs.put(p1, s);
ret = Math.min(ret, DFS(s+2, len, nums) );
swap(nums, s, p1_i);
indexs.put(num0, s);
indexs.put(p1, p1_i);
return ret+1;
}
public int minSwapPairs(int[][] pars, int[] nums, int n ){
if (pars == null || nums == null || pars.length == 0
|| nums.length ==0 || n == 0) return 0;
for (int[] par : pars) {
pairs.put(par[0], par[1]);
pairs.put(par[1], par[0]);
}
for (int i=0; i< (2*n); i++) {
indexs.put(nums[i], i);
}
return DFS(0, 2*n, nums);
}
I think greedy can apply to this problem:
suppose the pairs are
a1, a2
, b1, b2
, c1, c2
, so on and so force. (We assume that the alphabetical character is numberless here, in our analysis abc
is just enough)- separate the position of
arr[]
inton
groups - take group one for example, there are two numbers inside:
2.1 [a1, a2]. If the numbers inside are already a pair, skip to next group
2.2 [a1, b1]. We just assume that a1 is at its correct position and we need to swap b1 and a2. (We can prove that, it is no matter that we assume a1 or b1 at its correct position.) Count this swap and go on to the next group. - After the last group is processed, we can return how many swaps we have done.
We can scan it at first to record
Time Complexity: O(n) + O(n)
Space Complexity: O(n)
Read full article from Minimum number of swaps required for arranging pairs adjacent to each other - GeeksforGeekswhere is each number
by saving it into a hash map.Time Complexity: O(n) + O(n)
Space Complexity: O(n)