Smallest Subarray With Sum At Least Target

Implement smallestSubarrayWithSumAtLeastTarget

Given an array of positive integers nums and an integer target, find the length of the smallest contiguous subarray whose sum is greater than or equal to target. If no such subarray exists, return 0. Extending a window from every start and checking the sum works, but it re-derives the same ground repeatedly. A sliding windowSliding WindowMaintaining a running result over a contiguous range that grows or shrinks one element at a time, instead of recomputing the result for every range from scratch. with a variable size does better here: expand the right edge until the sum is enough, then greedily shrink the left edge for as long as it stays enough — every subarray that reaches target gets checked, but each element is added and removed from the running sum at most once, giving O(n) instead of O(n²).

Example 1:

Input: nums = [2,3,1,2,4,3], target = 7

Output: 2

Example 2:

Input: nums = [1,4,4], target = 4

Output: 1

Example 3:

Input: nums = [1,1,1,1,1,1,1,1], target = 11

Output: 0

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴
  • 1 ≤ target ≤ 10⁹

nums =

[2, 3, 1, 2, 4, 3]

target =

7