Minimum swaps and K together | Practice | GeeksforGeeks

Given an array arr of n positive integers and a number k. One can apply a swap operation on the array any number of times, i.e choose any two index i and j (i < j) and swap arr[i] , arr[j] . Find the minimum number of swaps required to bring all the numbers less than or equal to k together, i.e. make them a contiguous subarray.
Example 1:
Input : 
arr[ ] = {2, 1, 5, 6, 3} 
K = 3
Output : 
1
Explanation:
To bring elements 2, 1, 3 together,
swap index 2 with 4 (0-based indexing),
i.e. element arr[2] = 5 with arr[4] = 3
such that final array will be- 
arr[] = {2, 1, 3, 6, 5}


Example 2:
Input : 
arr[ ] = {2, 7, 9, 5, 8, 7, 4} 
K = 6 
Output :  
2 
Explanation: 
To bring elements 2, 5, 4 together, 
swap index 0 with 2 (0-based indexing)
and index 4 with 6 (0-based indexing)
such that final array will be- 
arr[] = {9, 7, 2, 5, 4, 7, 8}

 
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwap() that takes an array (arr), sizeOfArray (n), an integer K, and return the minimum swaps required. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ N ≤ 105
1 ≤ Arri, K ≤107
0
hr06in 8 hours
class Solution
{
   public:
   int minSwap(int arr[], int n, int k) {
       // Complete the function
       int less = 0;   // to keep track of elements less than / = K
       
       for(int i = 0; i<n; i++)
       {
           if(arr[i] <= k)
           {
               less++;
           }
       }
       
       // now check for windows of size less;
       
       int ans = INT_MAX;  // for updating to find out the minimum no of swaps
       
       int not_req = 0;
           
       // first process for the first window
       for(int i = 0; i<less; i++)
       {
           if(arr[i] > k)
           {
               not_req++;
           }
       }
       
       // ans for the first less size window
       ans = min(ans,not_req);
       
       
       // now process for the rest of the windows using Sliding window Algo
       for(int i = 0,j = less;j<n;j++,i++)
       {   
           // first removal 
           if(arr[i] > k)
           {
               not_req--;
           }
           
           // then addition
           if(arr[j] > k)
           {
               not_req++;
           }
           
           // now update the ans
           ans = min(ans,not_req);
       }
       
       return ans;
       
   }
};
0
mayankyadav252 weeks ago
c++ Solution
class Solution{public:   int minSwap(int arr[], int n, int k) {       // Complet the function       int good=0,bad=0;       for(int i=0;i<n;i++){           if(arr[i]<=k)           good++;       }       for(int i=0;i<good;i++){           if(arr[i]>k)           bad++;       }       int ans=bad;       for(int i=0,j=good;j<n;i++,j++){           if(arr[i]>k) bad--;           if(arr[j]>k) bad++;              ans=min(ans,bad);}       return ans;          }};
+1
nanawatiritik083 weeks ago
int count=0,countk=0,ans=INT_MAX;       for(int i=0;i<n;i++){           if(arr[i]<=k){               count++;           }       }       for(int i=0;i<count;i++){           if(arr[i]>k){               countk++;           }       }       ans=min(ans,countk);       int j=0;       for(int i=count;i<n;i++){           if(arr[j]>k){               countk--;           }           if(arr[i]>k){               countk++;           }           ans=min(ans,countk);           j++;                             }       return ans;
+2
gardnerchris3 weeks ago
Total Time Taken: 0.4/2.2
int minSwap(int a[], int n, int k) {
        int count=0;
        for(int i=0; i<n; i++) {
            if(a[i]<=k) count++;
        }
        if(count<2) return 0;
        int bad=0,curr=0,si=0;
        for(int i=0; i<count; i++) {
            if(a[i]>k) bad++;
        }
        curr=bad;
        for(int i=count; i<n; i++) {
            if(a[si]<=k&&a[i]>k) curr++;
            else if(a[si]>k&&a[i]<=k) curr--;
            bad=min(bad,curr);
            si++;
        }
        return bad;
    }
0
kushwaharajshree233 weeks ago
Sliding Window Technique in O(n) time and O(1) space.
int minSwap(int arr[], int n, int k) {
        // Complet the function
        int count = 0;
        for(int i=0;i<n;i++)
        {
            if(arr[i]<=k)
            count++;
        }
        int bad=0;
        for(int i=0;i<count;i++)
        {
            if(arr[i]>k)
            bad++;
        }
        int ans= bad;
        for(int i=0, j=count;j<n;i++,j++)
        {
            if(arr[i]>k)
            bad--;
            
            if(arr[j]>k)
            bad++;
            ans= min(ans, bad);
        }
        return ans;
    }
-2
charansaisadla1 month ago
def minSwap (arr, n, k) :    #Complete the function   count=0   for i in range(n):       if(arr[i]<=k):           count+=1   max1=count   bad=0   for i in range(count):       if(arr[i]>k):           bad=bad+1   ans=bad   limit=count   for i in range(n-k):       bad=0       for j in range(i+1,limit):           if(arr[j]>k):               bad+=1       ans=min(ans,bad)       limit+=1   return ans
THE CODE PRODUCES NO OUTPUT
0
charansaisadla
This comment was deleted.
+1
shivamray1 month ago
class Solution{public:   int minSwap(int arr[], int n, int k)   {       int legal=0,count=0,maxcount=0;       for(int i=0;i<n;i++)       {           if(arr[i]<=k)           legal++;       }       for(int i=0;i<legal;i++)       {           if(arr[i]<=k)           count++;       }       maxcount=count;       for(int j=legal;j<n;j++)       {           if(arr[j]<=k)           count++;           if(arr[j-legal]<=k)           count--;           maxcount=max(maxcount,count);                  }       return legal-maxcount;   }};
0
noob_7232 months ago
Time Complexity : O(N) 
Space Complexity : O(1)
 
Using Sliding Window Technique 
First count all the elements which are in the range
Then create a window of count each in the array and find where minimum number of swaps are required.
int minSwap(int v[], int n, int k) {
    	int count = 0;
    	for(int i = 0; i < n; i++) {
    		if(v[i] <= k) count++;
    	}
    
    	if(count == 0) return 0;
    
    	int i, j, bad, cc;
    	i = 0; 
    	j = 0;
    	cc = 0;
    	bad = INT_MAX;
    
    	while(j < n) {
    		if(v[j] > k) cc++;
    		// If window not reached 
    		if(j - i + 1 != count) {
    			j++;
    		}
    		else {
    			bad = min(bad, cc);
    			if(v[i] > k) cc--;
    			i++;
    			j++;
    		}
    	}
    
    	return bad;
    }
 
 
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.4 / 2.2 sec
 
int minSwap(int arr[], int n, int k) {       // using sliding window technique       int fav = 0;       for(int i = 0; i < n; i++){           if(arr[i] <= k) fav++;       }              int nfav = 0;       for(int i = 0; i < fav; i++){           if(arr[i] > k) nfav++;       }              int st = 0,en = fav-1;       int minSwaps = INT_MAX;       while(en < n){           minSwaps = min(minSwaps,nfav);           en++;           if(en < n && arr[en] > k) nfav++;           if(arr[st] > k) nfav--;           st++;       }              return minSwaps == INT_MAX ? 0 : minSwaps;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.