Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
l and r. Expand r to grow the window sum. Whenever total >= target, record the window size, then shrink from the left to try to find something smaller.A streaming system must dispatch a batch of packets whose total payload meets a minimum threshold. To minimize latency, it needs the shortest contiguous sequence of queued packets that hits that threshold. The variable sliding window scans the queue in a single pass — expanding to gather enough data and shrinking to minimize batch size — achieving O(n) without sorting or prefix-sum tables.
Since all numbers are positive, the window sum is monotonically increasing as we expand right. We exploit this to greedily shrink from the left whenever we overshoot the target, always tracking the minimum valid window length seen so far.
l = 0, total = 0, res = ∞.r: add nums[r] to total.total >= target: update res = min(res, r - l + 1), subtract nums[l] from total, increment l.0 if no valid window was found (res stayed ∞), else res.Each pointer moves at most n steps across the whole algorithm, giving O(n) time and O(1) extra space — no prefix sums or sorting required.
Discussion
…