Workspace Minimum Size Subarray Sum
0d
DSA Problem Sheet

Smallest Qualifying Window

Return the shortest contiguous length whose positive values sum to at least the positive target; return zero if impossible.

EXECUTION LAB

Return the shortest contiguous length whose positive values sum to at least the positive target; return zero if impossible.

Input and constraints
  • Each value must be positive.
  • Target must be a positive integer.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
left = 0
right = 0
total = 0
best = (len(values) + 1)
while (right < len(values)):
total = (total + values[right])
while (total >= target):
best = min(best, ((right - left) + 1))
total = (total - values[left])
left = (left + 1)
right = (right + 1)
if (best > len(values)):
return 0
return best

Visualizer

Step 1 of 12
02left, right
13
21
32
44
53

Expand the window at the current value

Expand the window at 0.

Variable watch

left 0right 0total 0

Step explanation

Expand the window at 0.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

Buy as few adjacent food parcels as possible while reaching a calorie goal.

Guided solution

Expand until a window qualifies, then shrink repeatedly to locate the shortest qualifying suffix.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[2,3,1,2,4,3],"target":7} ⇒ 2

Edge case 1 · {"values":[],"target":3} ⇒ 0

Edge case 2 · {"values":[1,2],"target":7} ⇒ 0

Progressive hints

Hint 1Buy as few adjacent food parcels as possible while reaching a calorie goal.
Hint 2Expand until a window qualifies, then shrink repeatedly to locate the shortest qualifying suffix.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Negative values would invalidate the monotonic shrinking argument.

Interview follow-up

Why does the inner loop still permit linear total work?