883232. Minimum Removals for Target Sum

Medium

Minimum Removals for Target Sum

Summary

The problem "Minimum Removals for Target Sum" involves given an array and a target sum, find the minimum number of elements that need to be removed from the array so that the remaining elements sum up to the target. This is a classic example of a problem that can be solved using the sliding window technique.

Detailed Explanation

To solve this problem, we will use a two-pointer approach. We initialize two pointers, left and right, both pointing to the start of the array. The idea is to maintain a sum of elements within the current window [left, right] that equals the target sum.

Here's the step-by-step breakdown:

  1. Initialize left and right to 0.
  2. Calculate the sum of the first right - left + 1 elements (arr[left:right+1]) and store it in a variable currentSum.
  3. If currentSum equals the target sum, return right - left + 1 (the number of elements in the current window).
  4. If currentSum is less than the target sum, increment right to move the window forward and recalculate currentSum.
  5. If currentSum is greater than the target sum, decrement left to shrink the window from the left side and recalculate currentSum.
  6. Repeat steps 2-5 until currentSum equals the target sum or we reach the end of the array.
  7. Return the minimum number of elements that need to be removed (which is the difference between the length of the original array and the length of the window where the sum equals the target).

Time complexity: O(n), where n is the length of the input array.

Space complexity: O(1), as we only use a constant amount of space to store the pointers and the sum.

Optimized Solutions

Java

View on GeeksforGeeks
public int minRemovals(int[] arr, int targetSum) {
    int left = 0;
    int right = 0;
    int currentSum = 0;
    int minRemovals = Integer.MAX_VALUE;

    while (right < arr.length) {
        currentSum += arr[right];
        while (currentSum > targetSum && left <= right) {
            currentSum -= arr[left++];
        }
        if (currentSum == targetSum) {
            minRemovals = Math.min(minRemovals, right - left + 1);
        }
        right++;
    }

    return minRemovals;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.