Minimum Size Subarray Sum
2 approaches, code in every language
Problem description
You are handed an array of positive integers together with a target value. Your job is to find the length of the shortest contiguous stretch of elements whose sum is at least as large as the target. When no stretch of the array can reach the target, report 0 instead.
Because every element is strictly positive, extending a window to the right can only increase its sum and dropping an element from the left can only decrease it. That monotonic behaviour is exactly what lets a single sweep find the shortest qualifying window.
Example 1
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
The two elements 4 and 3 sit next to each other and add up to 7, and no shorter run of elements manages to reach 7.
Example 2
Input: target = 4, nums = [1,4,4]
Output: 1
A single card holding 4 already meets the target on its own, so the minimal length is 1.
Constraints
1 ≤ target ≤ 10^91 ≤ nums.length ≤ 10^51 ≤ nums[i] ≤ 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Fewest Shifts to Clear the Quota is our own problem on the technique behind Minimum Size Subarray Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free