Smallest Qualifying Window
Return the shortest contiguous length whose positive values sum to at least the positive target; return zero if impossible.
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 bestVisualizer
Step 1 of 12Expand the window at the current value
Expand the window at 0.
Variable watch
Step explanation
Expand the window at 0.
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 1
Buy as few adjacent food parcels as possible while reaching a calorie goal.Hint 2
Expand until a window qualifies, then shrink repeatedly to locate the shortest qualifying suffix.Hint 3
Step 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?