Minimum Operations to Reduce X to Zero (LeetCode 1658): Solution and Explanation
Remove elements from either end of an array, subtracting each from x. Return the fewest removals that bring x to exactly 0, or -1 if it cannot be done.
Intuition
Trying every mix of left and right removals is a two-ended search that is hard to organize. Look at what stays instead: removing a prefix and a suffix always leaves one contiguous block in the middle.
The removed values add to x exactly when the kept block adds to total - x, where total is the sum of the whole array. So the question becomes: find the longest subarray whose sum is total - x.
Every value is positive, so adding an element always raises a window's sum and dropping one always lowers it. That makes a sliding window work: extend on the right, and shrink on the left while the sum is too big.
Whenever the window sum hits the target exactly, it is a candidate kept block. The answer is n minus the longest such block.
Approach: Sliding window for the longest block summing to total - x
- Compute
target = sum(nums) - x. If it is negative, return -1. - Set
left = 0,window = 0,best = -1. - For each
right, addnums[right]towindow. - While
window > target, subtractnums[left]and moveleftright. - If
window == target, setbest = max(best, right - left + 1). - Return -1 if
bestis still -1, otherwisen - best.
Step-by-step example
nums = [1,1,4,2,3], x = 5
- The total is 11, so the kept block must sum to 11 - 5 = 6.
- Indices 0, 1, 2 enter: 1 + 1 + 4 = 6. The block [1,1,4] has length 3, so
best = 3(2 removals). - Index 3 (2) pushes the sum to 8. Dropping the two 1s on the left brings it back to 6 with block [4,2], length 2, which is not longer.
- Index 4 (3) pushes the sum to 9. Dropping 4 leaves 5, which is below 6. The scan ends with
best = 3, so the answer is 5 - 3 = 2: remove 3 and 2 from the right.
Code: Python, Java, C++
1class Solution:
2 def minOperations(self, nums: List[int], x: int) -> int:
3 target = sum(nums) - x
4 if target < 0:
5 return -1
6 left = 0
7 window = 0
8 best = -1
9 for right in range(len(nums)):
10 window += nums[right]
11 while window > target:
12 window -= nums[left]
13 left += 1
14 if window == target:
15 best = max(best, right - left + 1)
16 return -1 if best == -1 else len(nums) - best1class Solution {
2 public int minOperations(int[] nums, int x) {
3 int target = -x;
4 for (int v : nums) target += v;
5 if (target < 0) return -1;
6 int left = 0, window = 0, best = -1;
7 for (int right = 0; right < nums.length; right++) {
8 window += nums[right];
9 while (window > target) {
10 window -= nums[left];
11 left++;
12 }
13 if (window == target) {
14 best = Math.max(best, right - left + 1);
15 }
16 }
17 return best == -1 ? -1 : nums.length - best;
18 }
19}1class Solution {
2public:
3 int minOperations(vector<int>& nums, int x) {
4 int target = -x;
5 for (int v : nums) target += v;
6 if (target < 0) return -1;
7 int left = 0, window = 0, best = -1;
8 for (int right = 0; right < (int)nums.size(); right++) {
9 window += nums[right];
10 while (window > target) {
11 window -= nums[left];
12 left++;
13 }
14 if (window == target) {
15 best = max(best, right - left + 1);
16 }
17 }
18 return best == -1 ? -1 : (int)nums.size() - best;
19 }
20};Time and space complexity
O(n)
Each index enters the window once and leaves it at most once.
O(1)
Only the two edges, the running sum and the best length are stored.
Other approaches
Prefix sums with a hash map (time O(n), space O(n))
Store the first index of each prefix sum. For each right end, look up prefix - target to find the leftmost start of a block with the target sum. This also works if values could be zero or negative.
Two pointers on prefix and suffix (time O(n), space O(1))
Take the largest prefix with sum at most x, then add suffix elements one at a time and drop prefix elements while the total is too big, checking for an exact hit. It is the same window viewed from the outside.
Try every prefix and suffix length (time O(n^2), space O(1))
For each count of left removals, scan suffix lengths for an exact sum. Correct but quadratic.
Common mistakes
- Using a greedy rule such as always removing the larger end. It can overshoot or miss the exact sum, as Example 3 shows.
- Forgetting the target = 0 case. Then the kept block is empty and the answer is n, which a window that requires length at least 1 would miss.
- Returning
bestinstead ofn - best. The window measures what you keep, not what you remove. - Not checking a negative target, which makes the shrinking loop run past the end of the array.
Frequently asked questions
Why look for the longest block instead of the shortest removal?
Removals always form a prefix plus a suffix, and the elements in between are a block whose length is n minus the removals. Maximizing that block is the same as minimizing removals, and a single block is easy to scan with a window.
Why does the sliding window need positive values?
With positive values, moving left forward always lowers the sum, so once the sum is too big the only fix is to shrink. With zeros or negatives that is no longer true, and the prefix-sum hash map is the safe choice.
What if x equals the whole array's sum?
Then the target is 0 and the kept block is empty. The window shrinks to nothing, records length 0, and the answer is n.