Minimum swaps required bring elements less equal K together

Pattern: Sliding window: fixed size

medium

Count the good values (at most k). They must end up in one block of that width, so slide a window of that width and find where the fewest bad values sit.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of whole numbers and a number k. One swap exchanges any two elements. Return the fewest swaps needed so that all values that are at most k sit next to each other. For example, [2, 1, 5, 6, 3] with k = 3 needs 1 swap (swap 5 and 3 to get [2, 1, 3, 6, 5]), and [2, 7, 9, 5, 8, 7, 4] with k = 6 needs 2.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name minSwap is this guide's own.

Think first

  • If there are g good values (at most k), how wide is the block they end up in?
  • Fix where that block goes. How many swaps does it take to fill it with good values?
  • Can a single swap fix more than one bad value inside the block?

Hints

    Brute force, and why it fails

    For each of the n - g + 1 block positions, count the bad values from scratch: O(n·g). Sliding the count makes it O(n). (This guide also checks its small tests with an exhaustive search over swap sequences.)

    The key insight

    The answer is a block whose width is known in advance: the number of good values. That turns "fewest swaps" into "fewest bad values in a fixed-size window".

    Dry run

    20 
    11 
    52 
    63 
    34 
    good3

    arr = [2, 1, 5, 6, 3] and k = 3. The good values (at most 3) are 2, 1 and 3, so the block must be 3 wide.

    Step 1 of 4

    The plan

    g = number of values that are at most k
    bad = number of values bigger than k in arr[0 .. g - 1]
    best = bad
    for right from g to n - 1:
        if arr[right] > k: bad = bad + 1           # entering
        if arr[right - g] > k: bad = bad - 1       # leaving
        best = min(best, bad)
    return best
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass to count the good values and one sliding pass, with a few counters.

    Edge cases

    • No good values, or only one: 0 swaps.
    • Every value is good: 0 swaps.
    • Good values already together, as in [1, 2, 3] with k = 5: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int minSwap(int[] arr, int k) {
            int n = arr.length;
            int good = 0;
            for (int v : arr) {
                if (v <= k) good++;                 // the block must be exactly this wide
            }
            int bad = 0;
            for (int i = 0; i < good; i++) {
                if (arr[i] > k) bad++;              // values that would have to be swapped out of the first window
            }
            int best = bad;
            for (int right = good; right < n; right++) {
                if (arr[right] > k) bad++;          // value entering the window
                if (arr[right - good] > k) bad--;   // value leaving the window
                best = Math.min(best, bad);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int minSwap(vector<int>& arr, int k) {
            int n = static_cast<int>(arr.size());
            int good = 0;
            for (int v : arr) {
                if (v <= k) good++;                 // the block must be exactly this wide
            }
            int bad = 0;
            for (int i = 0; i < good; i++) {
                if (arr[i] > k) bad++;              // values that would have to be swapped out of the first window
            }
            int best = bad;
            for (int right = good; right < n; right++) {
                if (arr[right] > k) bad++;          // value entering the window
                if (arr[right - good] > k) bad--;   // value leaving the window
                best = min(best, bad);
            }
            return best;
        }
    };

    Python

    class Solution:
        def minSwap(self, arr: list[int], k: int) -> int:
            good = sum(1 for v in arr if v <= k)    # the block must be exactly this wide
            bad = sum(1 for v in arr[:good] if v > k)
            best = bad
            for right in range(good, len(arr)):
                if arr[right] > k:
                    bad += 1                        # value entering the window
                if arr[right - good] > k:
                    bad -= 1                        # value leaving the window
                best = min(best, bad)
            return best

    Common mistakes

    • Counting good values in the window and returning that, instead of the bad ones.
    • Using a window width other than the number of good values.
    • Trying to move values next to their neighbours one step at a time. A swap may exchange any two positions.

    Similar problems