Minimum removals from array to make max –min <= K

Pattern: Sliding window: variable size

medium

Removing the fewest values means keeping the most. After sorting, the kept values are a block whose last minus first is at most k, so find the longest such window.

The problem

You are given an array of whole numbers and a number k. Remove as few elements as possible so that, among those left, the largest minus the smallest is at most k. Return how many you remove. For example, [1, 3, 4, 9, 10, 11, 12, 17, 20] with k = 4 needs 5 removals (keep 9, 10, 11 and 12), and [1, 5, 6, 2, 8] with k = 2 needs 3.

The link above is a GeeksforGeeks article on this problem. The function name minRemovals is this guide's own, and the function may sort the array.

Think first

  • Removing the fewest is the same as keeping the most. What do the kept values look like after sorting?
  • If you keep a smallest value a and a largest value b, which values in between should you also keep?
  • How do you find the longest stretch of sorted values with last minus first at most k?

Hints

    Brute force, and why it fails

    Try every subset to keep: 2^n subsets. Trying every pair of smallest and largest kept value and counting the values in between is O(n²) or O(n³). Sorting plus a window is O(n log n).

    The key insight

    After sorting, an optimal set of kept values is always one block, and the block's spread is just its last value minus its first. That makes it the longest valid window.

    Dry run

    10 
    31 
    42 
    93 
    104 
    115 
    126 
    177 
    208 
    k4

    arr = [1, 3, 4, 9, 10, 11, 12, 17, 20] (already sorted) and k = 4. Keep as many as possible in a window whose last minus first is at most 4.

    Step 1 of 4

    The plan

    sort arr
    left = 0, keep = 0
    for right from 0 to n - 1:
        while arr[right] - arr[left] > k:
            left = left + 1
        keep = max(keep, right - left + 1)
    return n - keep
    

    Complexity

    Time
    O(n log n)
    Space
    O(1)

    Sorting dominates. The window is O(n), with two indexes and one count.

    Edge cases

    • One element: 0 removals.
    • All values equal: 0 removals for any k ≥ 0.
    • k = 0: keep the most frequent value.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int minRemovals(int[] arr, int k) {
            Arrays.sort(arr);                       // the values we keep form a contiguous run once sorted
            int left = 0, keep = 0;
            for (int right = 0; right < arr.length; right++) {
                while (arr[right] - arr[left] > k) {
                    left++;                         // the smallest value is too far below arr[right]
                }
                keep = Math.max(keep, right - left + 1);
            }
            return arr.length - keep;
        }
    }

    C++

    class Solution {
    public:
        int minRemovals(vector<int>& arr, int k) {
            sort(arr.begin(), arr.end());           // the values we keep form a contiguous run once sorted
            int left = 0, keep = 0;
            for (int right = 0; right < static_cast<int>(arr.size()); right++) {
                while (arr[right] - arr[left] > k) {
                    left++;                         // the smallest value is too far below arr[right]
                }
                keep = max(keep, right - left + 1);
            }
            return static_cast<int>(arr.size()) - keep;
        }
    };

    Python

    class Solution:
        def minRemovals(self, arr: list[int], k: int) -> int:
            arr.sort()                              # the values we keep form a contiguous run once sorted
            left = keep = 0
            for right, v in enumerate(arr):
                while v - arr[left] > k:
                    left += 1                       # the smallest value is too far below arr[right]
                keep = max(keep, right - left + 1)
            return len(arr) - keep

    Common mistakes

    • Forgetting to sort, so a window's last minus first is not its spread.
    • Returning the size of the kept block instead of n minus it.
    • Removing values greedily from whichever end is further from the middle, which can fail when both ends are close.

    Similar problems