Minimum Operations to Reduce X to Zero

Take numbers from either end of an array until they add up to x, using as few as possible.

Given an array of positive integers nums and an integer x, bring x down to exactly 0. In one operation, remove either the leftmost or the rightmost number of the array and subtract it from x. Return the smallest number of operations that does it, or -1 if no sequence of operations can.

Example 1
Input: nums = [1, 1, 4, 2, 3], x = 5
Output: 2
Explanation: remove the last two numbers, 3 and 2.
Example 2
Input: nums = [5, 6, 7, 8, 9], x = 4
Output: -1
Example 3
Input: nums = [3, 2, 20, 1, 1, 3], x = 10
Output: 5
Explanation: remove the first two numbers and the last three.
Solution

The Idea

Picture six cards in a row: 3, 2, 20, 1, 1 and 3, as in Example 3. You may only take a card from one of the two ends of the row. You want the cards you take to add up to exactly 10, and you want to take as few cards as possible.

The 20 is the problem. Taking it already goes past 10, so the whole 10 must come from the cards around it. Taking 3 and 2 from the left gives 5, and taking 1, 1 and 3 from the right gives the other 5. That is five cards, the answer to Example 3.

In a longer row there are many ways to split the cards between the two ends: none from the left and some from the right, one from the left, two from the left, and so on. Each split needs its own count from the right. How can we find the best split without trying them all?

Look at what stays behind instead of what is taken. Whatever we take from the two ends, the cards that are left always sit next to each other in one unbroken stretch in the middle. Look at the picture below.

The array 3, 2, 20, 1, 1, 3 with x = 10. The numbers 3 and 2 are removed from the left and 1, 1 and 3 from the right, together 10. The kept middle is 20, which is the total 30 minus x.

The two cards marked "removed from the left" add up to 5, and the three marked "removed from the right" add up to 5 too. The orange box, the "kept middle", holds 20. All six cards add up to 30, and since the removed cards make 10, the kept middle must make 30 - 10 = 20.

That holds for every array. The kept middle always adds up to the total minus x, and removing as few cards as possible means keeping as many as possible. So the problem turns into a simpler one: find the longest stretch of neighbouring numbers whose sum is the total minus x. The answer is the length of the array minus the length of that stretch.

Solution Approach

Turning that idea into code means settling three things: what sum the middle must have, how to find the longest middle with that sum, and how to tell an empty middle apart from no middle at all.

The sum the middle must have

What should the kept middle add up to? Call it target: the sum of the whole array, total, minus x. In Example 2 the total is 35 and x is 4, so target is 31. No stretch of 5, 6, 7, 8, 9 adds up to 31, so the answer is -1.

If target is negative, x is bigger than the whole array. Even removing every number cannot reach it, so the answer is -1 before any search starts.

Finding the longest middle

How do we find the longest stretch with sum target? The simple way tries every start and every end and adds up the numbers between them. For 100,000 numbers that is about 5 billion pairs of start and end, which is far too slow.

A faster way uses two markers, left and right, at the two edges of the stretch being checked. This stretch is called a window. Each step moves right one place forward and adds the new number to the window's sum. While the sum is bigger than target, the number at left drops out and left moves forward. Both markers only ever move to the right, so the window slides along the array, and this way of searching is called the sliding window technique.

Why is it safe to move left forward for good? All the numbers are positive. If the window starting at left is already too big, making it longer only makes the sum bigger, so no stretch starting there can ever match.

Follow Example 3, where target is 20. The window takes 3, then 2, sum 5. Then it takes 20, sum 25, too big: 3 drops out (22), then 2 drops out (20). The window is now just [20], a match of length 1. Then 1 comes in, sum 21, and 20 drops out, leaving 1. The last three numbers only bring the sum up to 5, so the longest middle stays 1, and the answer is 6 - 1 = 5.

An empty middle

What if x equals the total? Then every number must go, the kept middle is empty, and target is 0. The window handles this too: each number it takes makes the sum bigger than 0, so it drops out again straight away, and the empty window has sum 0, a match of length 0.

So a length of 0 is a real answer. The value that means "no middle found yet" has to be something else, and -1 works, because no stretch has a negative length.

Java Solution

The method minOperations works in these steps:

  1. First, add up every number with a for-each loop into total.
  2. Compute target = total - x, the sum the kept middle must have. If it is negative, return -1.
  3. Set up the window: left starts at 0, the window's sum at 0, and longest at -1, meaning no middle found yet.
  4. A for loop moves right over the array and adds nums[right] to sum. Inside it, a while loop subtracts nums[left] and moves left forward for as long as sum is bigger than target.
  5. When sum equals target, the numbers from left to right form a valid middle, and its length right - left + 1 replaces longest if it is bigger.
  6. After the loop, return -1 if longest is still -1. Otherwise return nums.length - longest, the number of removed numbers.

The main method runs the three examples, an array where both removed numbers come from the left end, one where x equals the total, and one where x is bigger than the total.

Java
public class MinOperationsToReduceXToZero {

    public static int minOperations(int[] nums, int x) {
        int total = 0;
        for (int v : nums) {
            total += v;
        }
        int target = total - x;               // what the untouched middle part must sum to
        if (target < 0) {
            return -1;
        }
        int left = 0;
        int sum = 0;
        int longest = -1;                     // longest middle part with sum == target
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum > target) {
                sum -= nums[left];
                left++;
            }
            if (sum == target) {
                longest = Math.max(longest, right - left + 1);
            }
        }
        return longest == -1 ? -1 : nums.length - longest;
    }

    public static void main(String[] args) {
        System.out.println(minOperations(new int[] {1, 1, 4, 2, 3}, 5));
        System.out.println(minOperations(new int[] {5, 6, 7, 8, 9}, 4));
        System.out.println(minOperations(new int[] {3, 2, 20, 1, 1, 3}, 10));
        System.out.println(minOperations(new int[] {2, 3, 1, 1, 1}, 5));
        System.out.println(minOperations(new int[] {1, 2, 3}, 6));
        System.out.println(minOperations(new int[] {1, 2, 3}, 7));
    }
}

Running it prints:

Output
2
-1
5
2
3
-1

The answers 2, -1 and 5 match the three examples. In Example 1 the total is 11, so the kept middle must add up to 11 - 5 = 6. That is 1, 1, 4, three of the five numbers, so two numbers go.

The fourth line, 2, comes from [2, 3, 1, 1, 1] with x = 5. The kept middle is the three 1s at the end, so both removed numbers, 2 and 3, come from the left. The fifth line, 3, is the empty middle: 6 is the total of [1, 2, 3], so all three numbers go. The last line, -1, comes from the early check, because 7 is more than that total.

Why does longest start at -1 and not at 0? With 0, "no middle found" and "empty middle" look the same. Changed that way, the program prints 5 on its second line instead of -1, as if removing all of 5, 6, 7, 8, 9 brought 4 down to 0, though they add up to 35.

The original implementation, MinOperationsToReduceXToZero.java, is on GitHub.

Complexity

The work is one pass to add up the array, then one pass of the window.

  • Time: O(n), because the first loop reads each of the n numbers once, right visits each number once, and left only moves forward, so the while loop removes at most n numbers over the whole run.
  • Space: O(1), because the method keeps only total, target, sum, left and longest, and never copies the array.

Minimum Size Subarray Sum slides the same kind of window over positive numbers, but looks for the shortest stretch whose sum reaches a target.