![]() |
VOOZH | about |
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: 5After 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: 1
arr[2] can be swapped with arr[1] to get the required position.
Approach: This problem can be solved using greedy approach. Following are the steps :
Below is the implementation of above approach:
5
Complexity Analysis: