Minimum Size Subarray Sum

Find the shortest stretch of numbers next to each other whose sum is at least a target.

Given an array of positive integers nums and a positive integer target, find the shortest stretch of elements that sit next to each other, with no gaps, whose sum is at least target. Such a stretch is called a subarray. Return its length, or 0 if no subarray reaches target.

Example 1
Input: target = 7, nums = [2, 3, 1, 2, 4, 3]
Output: 2
Explanation: [4, 3] sums to 7, and no single element is 7 or more.
Example 2
Input: target = 4, nums = [1, 4, 4]
Output: 1
Explanation: [4] on its own is enough.
Example 3
Input: target = 11, nums = [1, 1, 1, 1, 1, 1, 1, 1]
Output: 0
Explanation: the whole array sums to only 8.
Solution

The Idea

Picture six jars of coins in a row, holding 2, 3, 1, 2, 4 and 3 coins. You need at least 7 coins, and you may only take jars that stand side by side. How few jars can you take? All six give 15 coins, far more than needed. The 4 and the 3 stand together and give exactly 7, and no single jar holds 7, so two jars is the answer. That is Example 1.

Six jars already allow 21 different side-by-side stretches, and a long row allows far more. Do we have to add up every one of them? Here is what helps: every number is positive. Adding a jar on the right always raises the sum, and dropping a jar on the left always lowers it.

So keep one stretch with a left edge and a right edge, and move only those edges. While the sum is too small, the right edge takes in the next jar. Once the sum is big enough, write down the length, then drop the jar on the left to see whether a shorter stretch still reaches 7. Look at the picture below.

The stretch moves over 2, 3, 1, 2, 4, 3 with target 7. Each row either grows it on the right or shrinks it on the left. Stretches whose sum is at least 7 are highlighted with their length, and the shortest is 4, 3 with length 2.

Before the first row, the right edge has already taken in 2, 3 and 1, for a sum of only 6. In the first row it takes in the next 2: the sum is 8, at least 7, so the length 4 is written down. The second row, labelled shrink, drops the first 2, and the sum falls to 6, too small. So the third row grows again by taking in the 4: 3, 1, 2, 4 sums to 10, still length 4.

The rows go on the same way. Shrinking to 1, 2, 4 still gives 7 with length 3, but 2, 4 gives only 6. The last grow takes in the 3: 2, 4, 3 sums to 9, again length 3. One more shrink leaves 4, 3, with sum 7 and length 2. Dropping the 4 leaves 3 alone, too small, and there is no jar left to take in. The shortest length written down is 2.

Each edge only ever moves to the right, so the whole search is one pass along the row. A stretch whose two edges move forward like this is called a sliding window, and Sliding Window Basics uses this problem as its main example.

Solution Approach

Turning that idea into code starts with seeing why the obvious way is too slow, then settling three things: when the window grows, how far it shrinks, and what to return when no window reaches target.

Trying every subarray

Why not just try them all? Start at each position and add numbers to the right until the sum reaches target. That gives the right answer, but each start may walk to the end of the array. For 100,000 numbers that is about 5 billion additions. The window adds each number once and removes it at most once.

Growing the window

When does the right edge move? On every step of one loop, which walks right from the first index to the last. Each step adds nums[right] to a running total, sum, which always holds the sum of the window, so nothing is ever added up twice.

Shrinking the window

How far should the left edge move after a step? As long as sum is still at least target: record the length, then drop nums[left] and move left one place right. That takes a loop, not a single step, because one large number can make several numbers on the left unneeded at once. In [1, 1, 10] with target 3, the 10 alone is enough, so both 1s have to go.

Can dropping a number on the left lose a better answer? A window that kept that number would have to end at the current right edge or later. Any such window is at least as long as the one just recorded, so it can never be shorter.

When no window is long enough

What if no subarray reaches target, as in Example 3? The shortest length found so far, best, starts at Integer.MAX_VALUE, the largest int, so any real length replaces it. If it is still there at the end, no window was ever recorded, and the answer is 0.

Java Solution

The method minSubArrayLen works in these steps:

  1. First, set the left edge left to 0, the running total sum to 0, and best, the shortest length found so far, to Integer.MAX_VALUE.
  2. Grow the window with a for loop that moves the right edge right from index 0 to the last index. Each step adds nums[right] to sum.
  3. Inside that loop, a while loop shrinks the window as long as sum is at least target. It keeps the window's length, right - left + 1, in best if it is shorter, subtracts nums[left] from sum, and moves left one place right.
  4. After the for loop, return 0 if best is still Integer.MAX_VALUE, and best otherwise.

The main method runs the three examples, then [1, 1, 10] with target 3, an array where only the whole array reaches the target, and an empty array.

Java
public class MinimumSizeSubArraySum {

    public static int minSubArrayLen(int target, int[] nums) {
        int left = 0;
        int sum = 0;                          // sum of nums[left..right]
        int best = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {           // valid: record it, then try a shorter one
                best = Math.min(best, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
        return best == Integer.MAX_VALUE ? 0 : best;
    }

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

Running it prints:

Output
2
1
0
1
3
0

The answers 2, 1 and 0 at the top match the three examples: [4, 3], then a single 4, then nothing, because eight 1s add up to only 8.

The fourth line, 1, is [1, 1, 10] with target 3. When right reaches the 10, sum is 12, and the while loop runs three times in that one step, recording 3, 2 and then 1. With an if in place of the while, the window loses at most one number per step. That version returns 3 here, and 4 instead of 2 for Example 1.

The fifth line, 3, comes from [1, 2, 3] with target 6, where only the whole array is enough. The last line is the empty array: the for loop never runs, best keeps Integer.MAX_VALUE, and the method returns 0.

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

Complexity

The work is two edges walking forward over the array, each at most once.

  • Time: O(n), because right visits each of the n numbers once, and left only moves forward, so the while loop runs at most n times in total across all steps.
  • Space: O(1), because the method keeps only left, right, sum and best, whatever the length of the array.

With negative numbers allowed, adding a number no longer always raises the sum, so the window loses its direction: see Shortest Subarray with Sum at Least K.