VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-adjacent-swaps-for-arranging-similar-elements-together/

⇱ Minimum number of adjacent swaps for arranging similar elements together - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of adjacent swaps for arranging similar elements together

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[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 :

  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:  


Output
5

Complexity  Analysis:

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