 Open in App
Not now

# Minimum number of adjacent swaps for arranging similar elements together

• Difficulty Level : Hard
• Last Updated : 26 Aug, 2022

Given an array of 2 * N positive integers where each array element lies between 1 to N and appears exactly twice in the array. The task is to find the minimum number of adjacent swaps required to arrange all similar array elements together.

Note: It is not necessary that the final array (after performing swaps) should be sorted.

Examples:

Input: arr[] = { 1, 2, 3, 3, 1, 2 }
Output: 5

After first swapping, array will be arr[] = { 1, 2, 3, 1, 3, 2 },
after second arr[] = { 1, 2, 1, 3, 3, 2 }, after third arr[] = { 1, 1, 2, 3, 3, 2 },
after fourth arr[] = { 1, 1, 2, 3, 2, 3 }, after fifth arr[] = { 1, 1, 2, 2, 3, 3 }

Input: arr[] = { 1, 2, 1, 2 }
Output:
arr can be swapped with arr to get the required position.

Approach: This problem can be solved using greedy approach. Following are the steps :

1. Keep an array visited[] which tells that visited[curr_ele] is false if swap operation has not been performed on curr_ele.
2. Traverse through the original array and if the current array element has not been visited yet i.e. visited[arr[curr_ele]] = false, set it to true and iterate over another loop starting from the current position to the end of array.
3. Initialize a variable count which will determine the number of swaps required to place the current element’s partner at its correct position.
4. In nested loop, increment count only if the visited[curr_ele] is false (since if it is true, means curr_ele has already been placed at its correct position).
5. If the current element’s partner is found in the nested loop, add up the value of count to the total answer.

Below is the implementation of above approach:

## C++

 `// C++ Program to find the minimum number of` `// adjacent swaps to arrange similar items together`   `#include ` `using` `namespace` `std;`   `// Function to find minimum swaps` `int` `findMinimumAdjacentSwaps(``int` `arr[], ``int` `N)` `{` `    ``// visited array to check if value is seen already` `    ``bool` `visited[N + 1];`   `    ``int` `minimumSwaps = 0;` `    ``memset``(visited, ``false``, ``sizeof``(visited));`   `    ``for` `(``int` `i = 0; i < 2 * N; i++) {`   `        ``// If the arr[i] is seen first time` `        ``if` `(visited[arr[i]] == ``false``) {` `            ``visited[arr[i]] = ``true``;`   `            ``// stores the number of swaps required to` `            ``// find the correct position of current` `            ``// element's partner` `            ``int` `count = 0;`   `            ``for` `(``int` `j = i + 1; j < 2 * N; j++) {`   `                ``// Increment count only if the current` `                ``// element has not been visited yet (if is` `                ``// visited, means it has already been placed` `                ``// at its correct position)` `                ``if` `(visited[arr[j]] == ``false``)` `                    ``count++;`   `                ``// If current element's partner is found` `                ``else` `if` `(arr[i] == arr[j])` `                    ``minimumSwaps += count;` `            ``}` `        ``}` `    ``}` `    ``return` `minimumSwaps;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 1, 2, 3, 3, 1, 2 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);` `    ``N /= 2;`   `    ``cout << findMinimumAdjacentSwaps(arr, N) << endl;` `    ``return` `0;` `}`

## Java

 `// Java Program to find the minimum number of` `// adjacent swaps to arrange similar items together` `import` `java.util.*;`   `class` `solution` `{`   `// Function to find minimum swaps` `static` `int` `findMinimumAdjacentSwaps(``int` `arr[], ``int` `N)` `{` `    ``// visited array to check if value is seen already` `    ``boolean``[] visited = ``new` `boolean``[N + ``1``];`   `    ``int` `minimumSwaps = ``0``;` `    ``Arrays.fill(visited,``false``);` `   `    `    ``for` `(``int` `i = ``0``; i < ``2` `* N; i++) {`   `        ``// If the arr[i] is seen first time` `        ``if` `(visited[arr[i]] == ``false``) {` `            ``visited[arr[i]] = ``true``;`   `            ``// stores the number of swaps required to` `            ``// find the correct position of current` `            ``// element's partner` `            ``int` `count = ``0``;`   `            ``for` `(``int` `j = i + ``1``; j < ``2` `* N; j++) {`   `                ``// Increment count only if the current` `                ``// element has not been visited yet (if is` `                ``// visited, means it has already been placed` `                ``// at its correct position)` `                ``if` `(visited[arr[j]] == ``false``)` `                    ``count++;`   `                ``// If current element's partner is found` `                ``else` `if` `(arr[i] == arr[j])` `                    ``minimumSwaps += count;` `            ``}` `        ``}` `    ``}` `    ``return` `minimumSwaps;` `}`   `// Driver Code` `public` `static` `void` `main(String args[])` `{` `    ``int` `arr[] = { ``1``, ``2``, ``3``, ``3``, ``1``, ``2` `};` `    ``int` `N = arr.length;` `    ``N /= ``2``;`   `    ``System.out.println(findMinimumAdjacentSwaps(arr, N));` `    `  `}` `}` `// This code is contributed by` `// Sanjit_Prasad`

## Python3

 `# Python3 Program to find the minimum number of ` `# adjacent swaps to arrange similar items together `   `# Function to find minimum swaps ` `def` `findMinimumAdjacentSwaps(arr, N) :` `    `  `    ``# visited array to check if value is seen already ` `    ``visited ``=` `[``False``] ``*` `(N ``+` `1``) `   `    ``minimumSwaps ``=` `0`   `    ``for` `i ``in` `range``(``2` `*` `N) : `   `        ``# If the arr[i] is seen first time ` `        ``if` `(visited[arr[i]] ``=``=` `False``) : ` `            ``visited[arr[i]] ``=` `True`   `            ``# stores the number of swaps required to ` `            ``# find the correct position of current ` `            ``# element's partner ` `            ``count ``=` `0`   `            ``for` `j ``in` `range``( i ``+` `1``, ``2` `*` `N) : `   `                ``# Increment count only if the current ` `                ``# element has not been visited yet (if is ` `                ``# visited, means it has already been placed ` `                ``# at its correct position) ` `                ``if` `(visited[arr[j]] ``=``=` `False``) :` `                    ``count ``+``=` `1`   `                ``# If current element's partner is found ` `                ``elif` `(arr[i] ``=``=` `arr[j]) :` `                    ``minimumSwaps ``+``=` `count ` `        `  `    ``return` `minimumSwaps`     `# Driver Code ` `if` `__name__ ``=``=` `"__main__"` `:`   `    ``arr ``=` `[ ``1``, ``2``, ``3``, ``3``, ``1``, ``2` `] ` `    ``N ``=` `len``(arr) ` `    ``N ``/``/``=` `2`   `    ``print``(findMinimumAdjacentSwaps(arr, N)) `   `# This code is contributed by Ryuga`

## C#

 `// C# Program to find the minimum ` `// number of adjacent swaps to ` `// arrange similar items together ` `using` `System; `   `class` `GFG ` `{ `   `    ``// Function to find minimum swaps ` `    ``static` `int` `findMinimumAdjacentSwaps(``int` `[]arr, ``int` `N) ` `    ``{ ` `        ``// visited array to check` `        ``// if value is seen already ` `        ``bool``[] visited = ``new` `bool``[N + 1]; `   `        ``int` `minimumSwaps = 0; `     `        ``for` `(``int` `i = 0; i < 2 * N; i++) ` `        ``{ `   `            ``// If the arr[i] is seen first time ` `            ``if` `(visited[arr[i]] == ``false``) ` `            ``{ ` `                ``visited[arr[i]] = ``true``; `   `                ``// stores the number of swaps required to ` `                ``// find the correct position of current ` `                ``// element's partner ` `                ``int` `count = 0; `   `                ``for` `(``int` `j = i + 1; j < 2 * N; j++)` `                ``{ `   `                    ``// Increment count only if the current ` `                    ``// element has not been visited yet (if is ` `                    ``// visited, means it has already been placed ` `                    ``// at its correct position) ` `                    ``if` `(visited[arr[j]] == ``false``) ` `                        ``count++; `   `                    ``// If current element's partner is found ` `                    ``else` `if` `(arr[i] == arr[j]) ` `                        ``minimumSwaps += count; ` `                ``} ` `            ``} ` `        ``} ` `        ``return` `minimumSwaps; ` `    ``} `   `    ``// Driver Code ` `    ``public` `static` `void` `Main(String []args) ` `    ``{ ` `        ``int` `[]arr = { 1, 2, 3, 3, 1, 2 }; ` `        ``int` `N = arr.Length; ` `        ``N /= 2; `   `        ``Console.WriteLine(findMinimumAdjacentSwaps(arr, N)); ` `    ``} ` `} `   `// This code is contributed by PrinciRaj1992`

## Javascript

 ``

Output

`5`

Complexity  Analysis:

• Time Complexity: O(N2
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles