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
+1
naman77564 days ago
C++ solution Easy
 
int minSwap(int a[], int n, int k) {
        int count=0;
        for(int i=0; i<n; ++i){
            if(a[i]<=k){
                count++;
            }
        }
        int cnt=0, ans=INT_MAX;
        for(int i=0; i<count; ++i){
            if(a[i]<=k){
                cnt++;
            }
        }
        ans=count-cnt;

        for(int i=1; i<=n-count; ++i){
            if(a[i-1]<=k){
            cnt--;
            }
            if(a[i+count-1]<=k){
            cnt++;
            }
           
            ans=min(count-cnt, ans);
        //      cout<<i<<endl;
        //             cout<<ans<<endl;
        // cout<<count<<endl;
        // cout<<cnt<<endl<<endl;
        }
        return ans;
    }
 
 
-3
singhchandankumariit2 weeks ago
int minSwap(int arr[], int n, int k) {       int cnt=0;       for(int i=0;i<n;i++){           if(arr[i]<=k)cnt++;       }              for(int i=0;i<n;i++)           if(arr[i]<=k)arr[i]=0;              int cnt0=0;       for(int i=0;i<cnt;i++)           if(arr[i]==0)cnt0++;              int mx=cnt0;       int i=cnt;              while(i<n){           if(arr[i]==0&&arr[i-cnt]!=0)cnt0++;           else if(arr[i]!=0&&arr[i-cnt]==0)cnt0--;           mx=max(mx,cnt0);                     i++;       }              return cnt-mx;        }
+4
mandeepjain002 weeks ago
Problem statement
we make swap in such way that all element in array less than k should arranged in continusly (order is not req) but that swaps should be minimum
 
Approach
first calculate total number of element in array which is less than k (that beacomes a window size)
then start window slide algoif greater than k (arr[j] > k) element come in window we increase bad++when we hit window size (j-i+1 == count) we check for min of bad and slide the window by checking if ith element is is contibuting in bad tou make bad-- and do  i++
COde
 
 
 
 int minSwap(int arr[], int n, int k) {
        // Complet the function
       int count = 0;//number of element less than or equal k (window size)
       for(int i=0; i<n; i++)
           if(arr[i] <= k)count++;
           
    //koi element chota hai hi ni tou kese
           if(count == 0) return 0;
        int i=0, j=0;
        int bad = 0;
        int ans = INT_MAX;
        
        while(j < n){
            if(arr[j] > k) bad++; //curr window me kitne greater k ele(jinko swap krna hoga)
            if(j-i+1 < count) j++;
            else if(j-i+1 == count){
                ans = min(ans, bad);
                //slide windlow
                if(arr[i] > k) bad--;
                i++,j++;
            }
        }
        return ans;
       
    }
+1
numaan_esc3 weeks ago
Solved with JAVA. All test cases passed.
For any query comment down below.
Sliding Window technique used
 
public static int minSwap (int[] arr, int n, int k) {
        // number of element smaller than and equal to K
        int totalEle = 0;

        // finding number of element through this loop
        for(int i = 0; i < n; i++)
            if(arr[i] <= k)
                totalEle++;

        // if there is no small element in the array then we'll print 0
        if(totalEle == 0)
            return 0;

        // finding element in first window( of size totalEle) which is less than and equal to K
        int i;
        // Count in first window
        int count = 0;
        for(i = 0; i < totalEle; i++)
            if(arr[i] <= k)
                count++;

        // Initialise maxCount as to check which window has the highest number of element in every window of size totalEle
        int maxCount = count;
        
        while(i < n){
            // while moving to next window, we have to check 2 points
            // 1 - last element which is going to be kicked less than or equal to K or not
            // if yes then we'll decrement the count
            if(arr[i-totalEle] <= k)
                count--;
            // 2 - element at index i is less than or equal to K or not
            // if yes then we'll increment the count
            if(arr[i] <= k)
                count++;

            // we'll keep note that which windows has the highest amount of elements belongs to this category (<=K)
            maxCount = Math.max(maxCount, count);
            i++;
        }

        // then to sum up, after getting window with maximum number of elements (<=K)
        // we'll just subtract it with total elements which is <=K
        // in order to get the amount of min swap
        return totalEle - maxCount;
    }
0
lloda2973 weeks ago
PROPER STEP-BY STEP EXPPLANATION USING SLIDING WINDOW TECHNIQUE
class Solution
{
public:
    int minSwap(int arr[], int n, int k) {
        deque<int>dq;          
        int count=0;
        for(int i=0;i<n;i++){        // LOOP TO FIND HOW MANY ELEMENTS
            if(arr[i]<=k){           //  ARE <=K IN THE ARRAY
                count++;
            }
        }
        int count2=0,maximumer=INT_MIN;
        for(int i=0;i<count;i++){     //LOOP INITIATES THE SLIDING WINDOW
            dq.push_back(arr[i]);     //WITH 1ST SET OF NUMBERS. THE WINDOW 
            if(dq.back()<=k){         //SIZE='NO. OF ELEMENTS<=K'
                count2++;
            }
        }
        maximumer=max(maximumer,count2);
        for(int j=count;j<n;j++){ //TO SLIDE THE WINDOW BY ELIMINATING FROM 
            if(dq.front()<=k){    //FRONT AND PUSHING AT BACK SIMULTANEOUSLY
                count2--;         
            }
            dq.pop_front();
            if(arr[j]<=k){
                count2++;
            }
            dq.push_back(arr[j]);           //MAX THE GROUP OF SUCH NO. PRESENT 
            maximumer=max(maximumer,count2); //MIN THE REQUIRED OPERATIONS BE
        }
        return count-maximumer;              //RETURN MIN. REQUIRED OPERATIONS
    }
};
 
0
mrajneesh7233 weeks ago
Sliding Window Approach:
class Solution    //MT :){public:        int minSwap(int arr[], int n, int k) {       int cnt=0;       for(int i=0;i<n;i++){           if(arr[i]<=k)cnt++;       }       int ans=0;       int fans=0;       for(int i=0;i<cnt;i++){           if(arr[i]<=k)ans++;       }       fans=max(ans,fans);       for(int i=cnt;i<n;i++){           if(arr[i-cnt]<=k)ans--;           if(arr[i]<=k)ans++;           fans=max(ans,fans);       }       return cnt-fans;       // Complet the function   }};
+2
ruchitchudasama1233 weeks ago
public:
    int minSwap(int arr[], int n, int k) {
        int wsize=0;
        for(int i=0;i<n;i++){
            if(arr[i]<=k)wsize++;        
        }
        int count=0;
        for(int i=0;i<wsize;i++){
            if(arr[i]<=k)count++;
        }
        int ans=wsize-count;
        for(int i=wsize;i<n;i++){
            if(arr[i-wsize]<=k)count--;
            if(arr[i]<=k)count++;
            ans=min(ans,wsize-count);
        }
        return ans;
    }
0
yashmandaviya7021 month ago
int minSwap(int v[], int n, int k) {       // Complet the function       int c=0;    for(int i=0;i<n;i++) if(v[i]<=k) c++;    int ans = INT_MAX;    int inwindow=0;    for(int i=0;i<n;i++){     if(i<c) {if(v[i]<=k)inwindow++;}     else{      if(v[i]<=k) inwindow++;      if(v[i-c]<=k && inwindow>0) inwindow--;     }        ans=min(ans,c-inwindow);    }    return ans;   }
+1
madhukartemba1 month ago
JAVA SOLUTION USING SLIDING WINDOW:
class Complete{
    
   
    // Function for finding maximum and value pair
    public static int minSwap (int arr[], int n, int k) {
        
        int n_ele = 0;
        
        for(int x : arr)
        {
            if(x<=k) n_ele++;
        }
        
        int l = 0;
        
        int count = 0;
        
        int max_count = 0;
        
        for(int r=0; r<n; r++)
        {
            if(r>=n_ele)
            {
                if(arr[l]<=k)
                {
                    count--;
                    
                }
                
                l++;
            }
            
            if(arr[r]<=k) count++;
            
            max_count = Math.max(max_count, count);
        }
        
        
        return n_ele - max_count;
        
    }
    
    
}
0
anupkumarmridhanet1 month ago
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 requiredSwap=0;       for(int i=0;i<count;i++){           if(arr[i]>k){               requiredSwap++;           }       }              int ans=requiredSwap;              for(int i=0, j=count; j<n;i++,j++){           if(arr[i]>k){               requiredSwap--;           }           if(arr[j]>k)               {                   requiredSwap++;               }           ans=min(ans,requiredSwap);           }       return ans;   }
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.