Sliding Window · Variable size

Minimum Size Subarray Visualizer

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

Try every blockPositive numbers make a shorter block inside a longer one have a smaller sum, so the two-end scan does not miss the shortest block. Checking every pair is still too slow.
Expand, then shrinkThe right edge only moves forward. Whenever the sum is large enough, the left edge moves forward too, and the smallest length seen is the answer.

Interactive solution

The sum inside the window against the target
for each new value, add it
while the sum reaches the target, remember the length and drop the left value
return the shortest length, or 0
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each index is added once and removed once.
MemoryO(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