Minimum swaps required to bring all elements less than or equal to k together in C++


Problem statement

Given an array of n positive integers and a number k. Find the minimum number of swaps required to bring all the numbers less than or equal to k together.

Example

If input array is = {1, 5, 4, 7, 2, 10} and k = 6 then 1 swap is required i.e. swap element 7 with 2.

Algorithm

  • Count all elements which are less than or equals to ‘k’. Let’s say the count is ‘cnt’
  • Using two pointer technique for window of length ‘cnt’,each time keep track of how many elements in this range are greater than ‘k’. Let’s say the total count is ‘outOfRange’.
  • Repeat step 2, for every window of length ‘cnt’ and take minimum of count ‘outOfRange’ among them. This will be the final answer.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinSwaps(int *arr, int n, int k) {
   int cnt = 0;
   for (int i = 0; i < n; ++i) {
      if (arr[i] <= k) {
         ++cnt;
      }
   }
   int outOfRange = 0;
   for (int i = 0; i < cnt; ++i) {
      if (arr[i] > k) {
         ++outOfRange;
      }
   }
   int result = outOfRange;
   for (int i = 0, j = cnt; j < n; ++i, ++j) {
      if (arr[i] > k) {
         --outOfRange;
      }
      if (arr[j] > k) {
         ++outOfRange;
      }
      result = min(result, outOfRange);
   }
   return result;
}
int main() {
   int arr[] = {1, 5, 4, 7, 2, 10};
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 6;
   cout << "Minimum swaps = " << getMinSwaps(arr, n, k) <<
   endl;
   return 0;
}

When you compile and execute above program. It generates following output −

Output

Minimum swaps = 1

Updated on: 20-Dec-2019

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements