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
- Calculate
target = total - x. This is the sum we want the middle subarray to have. - Use two pointers
landrto define the current window, withcurSumtracking the window sum. - Expand
rto include elements. IfcurSumexceedstarget, shrink fromluntilcurSum <= target. - When
curSum == target, record thewindowlength if it is themaxseen. - The answer is
n - maxWindow. Return-1if 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.