What is Minimum Size Subarray
Every value is positive. Return the length of the shortest contiguous block whose sum is at least target. If no block is large enough, return 0. Grow until the sum qualifies, then shrink from the left while it still qualifies.
2 3 1 2 4 3 target 7 2
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is added once and removed once. |
| Memory | O(1) | Only the sum, the ends, and the best length are stored. |
Implementation
def min_size(a, target):
l = cur = best = 0
for r, v in enumerate(a):
cur += v
while cur >= target and l <= r:
length = r - l + 1
best = length if best == 0 else min(best, length)
cur -= a[l]
l += 1
return best