Minimum Size Subarray Sum

Problem Given an array of positive integers and a target sum, find the minimal length of a contiguous subarray whose sum is greater than or equal to the target. Return 0 if no such subarray exists.

Input / Output

  • Input: integer target, array nums of positive integers.
  • Output: the length of the shortest qualifying subarray, or 0 if none exists.

Constraints

  • Array length up to 10^5.
  • All elements are strictly positive — this is the load-bearing constraint that makes the sliding window valid.
  • The subarray must be contiguous.

Example

  • target = 7, nums = [2,3,1,2,4,3] → 2, from [4,3].
  • Tricky: target = 11, nums = [1,1,1,1,1] → 0 (whole array sums to 5). target = 4, nums = [1,4,4] → 1 — a single element can satisfy the target, so the window must shrink to length 1.
asked …
LeaderboardSalaryAccount