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 numstargettargettarget
Example 1
Output: 2
Explanation: [4, 3] sums to 7, and no single element is 7 or more.
Example 2
Output: 1
Explanation: [4] on its own is enough.
Example 3
Output: 0
Explanation: the whole array sums to only 8.
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.
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
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
Growing the window
When does the right edge move? On every step of one loop, which walks rightnums[right]sum
Shrinking the window
How far should the left edge move after a step? As long as sumtargetnums[left]left[1, 1, 10]
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 targetbestInteger.MAX_VALUEint
Java Solution
The method minSubArrayLen
- First, set the left edge
to 0, the running totalleft to 0, andsum , the shortest length found so far, tobest .Integer.MAX_VALUE - Grow the window with a
loop that moves the right edgefor from index 0 to the last index. Each step addsright tonums[right] .sum - Inside that loop, a
loop shrinks the window as long aswhile is at leastsum . It keeps the window's length,target , inright - left + 1 if it is shorter, subtractsbest fromnums[left] , and movessum one place right.left - After the
loop, return 0 iffor is stillbest , andInteger.MAX_VALUE otherwise.best
The main[1, 1, 10]
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:
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]rightsumwhileifwhile
The fifth line, 3, comes from [1, 2, 3]forbestInteger.MAX_VALUE
The original implementation,
Complexity
The work is two edges walking forward over the array, each at most once.
- Time: O(n), because
visits each of the n numbers once, andright only moves forward, so theleft loop runs at most n times in total across all steps.while - Space: O(1), because the method keeps only
,left ,right andsum , whatever the length of the array.best
With negative numbers allowed, adding a number no longer always raises the sum, so the window loses its direction: see