Minimum Operations to Reduce X to Zero

Problem

Given an array and an integer x, find the minimum number of elements to remove from either end so the sum of the removed elements equals exactly x.

Input:  nums = [1,1,4,2,3], x = 5
Output: 2   (remove 4 and 1 from the right)

Python Solution

def min_operations(nums, x):
    total = sum(nums)
    target = total - x
    if target < 0:
        return -1
    if target == 0:
        return len(nums)
    left = 0
    window_sum = 0
    best_len = -1
    for right, num in enumerate(nums):
        window_sum += num
        while window_sum > target:
            window_sum -= nums[left]
            left += 1
        if window_sum == target:
            best_len = max(best_len, right - left + 1)
    return len(nums) - best_len if best_len != -1 else -1

C++ Solution

int minOperations(vector<int>& nums, int x) {
    long total = 0;
    for (int n : nums) total += n;
    long target = total - x;
    if (target < 0) return -1;
    if (target == 0) return nums.size();
    int left = 0, bestLen = -1;
    long windowSum = 0;
    for (int right = 0; right < nums.size(); right++) {
        windowSum += nums[right];
        while (windowSum > target) {
            windowSum -= nums[left];
            left++;
        }
        if (windowSum == target) bestLen = max(bestLen, right - left + 1);
    }
    return bestLen == -1 ? -1 : (int)nums.size() - bestLen;
}

Java Solution

class Solution {
    public int minOperations(int[] nums, int x) {
        long total = 0;
        for (int n : nums) total += n;
        long target = total - x;
        if (target < 0) return -1;
        if (target == 0) return nums.length;
        int left = 0, bestLen = -1;
        long windowSum = 0;
        for (int right = 0; right < nums.length; right++) {
            windowSum += nums[right];
            while (windowSum > target) {
                windowSum -= nums[left];
                left++;
            }
            if (windowSum == target) bestLen = Math.max(bestLen, right - left + 1);
        }
        return bestLen == -1 ? -1 : nums.length - bestLen;
    }
}

Complexity

Time: O(n) — the left pointer only moves forward. Space: O(1) — only running sums. Key trick: removing the minimum from both ends to sum x is the same as finding the longest middle subarray summing to total - x.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.