Minimum Operations to Reduce X to Zero

Medium · Sliding Window · Explanation and code example

Sliding Window

How it works

Building on the same insight as the hash map approach, we want the longest subarray summing to target = total - x. Since all elements are positive, the subarray sum increases as we expand and decreases as we shrink. This monotonic property allows us to use a sliding window: expand the right boundary to include more elements, and shrink from the left when the sum exceeds the target.

Steps

  1. Calculate target = total - x. This is the sum we want the middle subarray to have.
  2. Use two pointers l and r to define the current window, with curSum tracking the window sum.
  3. Expand r to include elements. If curSum exceeds target, shrink from l until curSum <= target.
  4. When curSum == target, record the window length if it is the max seen.
  5. The answer is n - maxWindow. Return -1 if no valid window was found.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1) extra space.

Things to watch for

Not Recognizing the Problem Transformation

The key insight is that removing elements from both ends that sum to x is equivalent to finding the longest contiguous subarray that sums to total - x. Many solutions fail because they try to directly simulate removing from both ends, leading to inefficient or incorrect approaches.

Forgetting to Handle Edge Cases

When total == x, the answer is n (remove all elements). When total < x, the answer is -1 (impossible). When target = total - x is negative, return -1. Missing any of these edge cases causes wrong answers on specific test cases.

Overlapping Prefix and Suffix in Brute Force

In approaches that combine prefix and suffix sums, you must ensure the prefix and suffix do not overlap (i.e., the suffix must start after the prefix ends). A common bug is allowing j <= i instead of j > i, which double-counts elements and produces incorrect results.

Python code example

from typing import List

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        target = sum(nums) - x
        cur_sum = 0
        max_window = -1
        l = 0

        for r in range(len(nums)):
            cur_sum += nums[r]

            while l <= r and cur_sum > target:
                cur_sum -= nums[l]
                l += 1

            if cur_sum == target:
                max_window = max(max_window, r - l + 1)

        return -1 if max_window == -1 else len(nums) - max_window

C++ code example

class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int target = accumulate(nums.begin(), nums.end(), 0) - x;
        int curSum = 0, maxWindow = -1, l = 0;

        for (int r = 0; r < nums.size(); r++) {
            curSum += nums[r];

            while (l <= r && curSum > target) {
                curSum -= nums[l];
                l++;
            }

            if (curSum == target) {
                maxWindow = max(maxWindow, r - l + 1);
            }
        }

        return maxWindow == -1 ? -1 : nums.size() - maxWindow;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations