Minimum Swaps Required to Bring Elements Less Than or Equal to k Together
Fri Mar 15 2024
minSwap :
Function to calculate the minimum number of swaps required to bring all elements less than or equal to k together in an array. This approach first counts the number of elements (favourable) that meet the condition. Then, it finds the initial count of nonFavourable elements within the first window of size favourable. Subsequently, it slides the window across the array, updating the count of nonFavourable elements and recording the minimum swaps needed to align all favourable elements contiguously.
1let arr =[2, 1, 5, 6, 3]
2let k = 3
3function minSwap(arr,k){
4    let favourable = 0;
5    let nonFavourable = 0;
6    for(let i = 0; i<arr.length; i++){
7        if(arr[i]<=k){
8            favourable++
9        }
10    }
11    for(let j = 0; j<favourable; j++){
12        if(arr[j]>k){
13            nonFavourable++
14        }
15    }
16   
17    let swap = nonFavourable
18
19    for(let i = 0, j = favourable; j < arr.length; ++i, ++j){
20        if(arr[i] > k){
21            --nonFavourable
22        }
23        if(arr[j] > k){
24            ++nonFavourable
25        }
26        swap = Math.min(nonFavourable,swap);
27    }
28    return swap;
29    
30}
31
32console.log(minSwap(arr,k))