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

 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.




Input: arr[] = {2, 1, 5, 6, 3}, k = 3

Output: 1

Explanation: To bring elements 2, 1, 3 together, swap element ‘5’ with ‘3’ such that final array will be arr[] = {2, 1, 3, 6, 5}


Input: arr[] = {2, 7, 9, 5, 8, 7, 4}, k = 5

Output: 2

📝 Explanation

  1. Find the window size → Count numbers k.

  2. Calculate "bad" elements (elements > k) in the first window.

  3. Use Sliding Window:

    • Move the window right (remove old, add new).

    • Track the minimum "bad" count (which gives the min swaps).

  4. Return minSwaps as the answer.

 Takeaways

✅ We only check a window onceO(n) efficiency
✅ The bad count helps track unnecessary swaps
✅ Sliding one step at a time avoids nested loops (faster)


Step-by-Step Execution

Step 1: Calculate count (Window Size)

The window size is the count of elements k.

  • Elements 3 in {2, 1, 5, 6, 3}{2, 1, 3}

  • Total count = 3

  • So, the window size is 3.

int count = 0;
for (int num : arr) {
    if (num <= k) count++;
}

🔹 After loop execution:
count = 3

Step 2: Count "bad" elements in the first window

A "bad" element is any number greater than k.

First window (size = 3) = {2, 1, 5}

  • 2 → ✅ Good (≤ k)

  • 1 → ✅ Good (≤ k)

  • 5 → ❌ Bad (> k)

int bad = 0;
for (int i = 0; i < count; i++) {  
    if (arr[i] > k) bad++;  
}

🔹 bad = 1

Step 3: Slide the Window and Minimize "bad" elements

Now, we move the window right and update bad.

Iteration 1 (i = 3)

  • Old window: {2, 1, 5}

  • New window: {1, 5, 6}

  • Removed: 2 (✅ Good, no change in bad)

  • Added: 6 (❌ Bad, bad++)

bad = 2, but minSwaps = min(1, 2) = 1

Iteration 2 (i = 4)

  • Old window: {1, 5, 6}

  • New window: {5, 6, 3}

  • Removed: 1 (✅ Good, no change in bad)

  • Added: 3 (✅ Good, bad--)

bad = 1, so minSwaps = min(1, 1) = 1


Final Answer

After checking all windows, the minimum swaps needed = 1.


Minimum swaps needed: 1

🔄 Code Flow Summary

StepWindowRemovedAddedBad CountminSwaps
Start{2,1,5}--11
Move Right{1,5,6}2621
Move Right{5,6,3}1311

public class codefile{
    static int solve(int[]  input,int k){
       
          int n = input.length;
       
        // Step 1: Count elements ≤ k (this gives us the window size)
        int count = 0;
        for (int num : input) {
            if (num <= k) count++;
        }

        // If count is 0 or already grouped, no swaps needed
        if (count == 0 || count == n) return 0;

        // Step 2: Count "bad" elements in the first window
        int bad = 0;
        for (int i = 0; i < count; i++) {
            if (input[i] > k) bad++;
        }

        // Step 3: Use Sliding Window to find the minimum "bad" elements
        int minSwaps = bad;
        for (int i = count; i < n; i++) {
            // Remove outgoing element from the left
            if (input[i - count] > k) bad--;

            // Add incoming element from the right
            if (input[i] > k) bad++;

            // Update the minimum swaps needed
            minSwaps = Math.min(minSwaps, bad);
        }

        return minSwaps;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence