InterviewPrepKit

Home / Coding / Sliding Window

Minimum Size Subarray Sum

medium Original β†—
Solving tips
  • Because all elements are positive the window sum is monotone, enabling a shrinking window: grow right adding to a running sum, then shrink left while sum >= target.
  • This is a minimum-length problem, so record right-left+1 INSIDE the shrink loop while the window is still valid, not after.
  • Target O(n) time and O(1) space; return 0 (converting the n+1/inf sentinel) when no subarray qualifies.
  • Common pitfall: use >= not > (to catch exact target hits), and note the template breaks with negative numbers, which need prefix sums plus binary search or a deque.

Problem

Given an array nums of positive integers and a positive integer target, return the length of the shortest contiguous subarray whose sum is greater than or equal to target. If no subarray reaches target, return 0.

Two details matter: elements are strictly positive (this is what makes the fast solution work), and you want the minimum length β€” a reversal of the more common β€œlongest valid window” setup.

Examples

  • target = 7, nums = [2, 3, 1, 2, 4, 3] β†’ 2 β€” [4, 3] sums to 7; no single element reaches 7.
  • target = 4, nums = [1, 4, 4] β†’ 1 β€” a single 4 already meets the target.
  • target = 11, nums = [1, 1, 1, 1, 1] β†’ 0 β€” the whole array sums to 5, so no valid subarray exists.

Constraints

  • 1 <= target <= 10^9
  • 1 <= len(nums) <= 10^5
  • 1 <= nums[i] <= 10^4

O(nΒ²) subarray enumeration is ~5 * 10^9 steps at n = 10^5. The expected solution is O(n); an O(n log n) prefix-sum + binary-search solution is a classic follow-up.

Think about it first

Hint 1 Because every element is positive, growing a window strictly increases its sum and shrinking strictly decreases it. Which direction do you move when the sum is too small? When it's big enough?
Hint 2 You want the shortest window meeting the target β€” so once the window's sum reaches target, greedily shrink it from the left while it still qualifies, recording each qualifying length.
Hint 3 One pass: extend right, adding to a running sum; then while sum >= target, record right - left + 1 and subtract nums[left], advancing left. Each pointer moves at most n times.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.