Back to ArraysSmallest Subarray with Sum ≥ Target
Medium

Smallest Subarray with Sum ≥ Target

MediumRecommendedSliding Window

Given an array of positive integers and a target sum, find the length of the shortest contiguous subarray whose sum is at least the target. Return 0 if no such subarray exists.

Examples

Example 1

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

Explanation: The subarray [4,3] (indices 4-5) sums to 7 with length 2 — the shortest qualifying subarray.

Example 2

Input:
nums = [1,2,3], target = 100
Output:
0

Explanation: No subarray's sum ever reaches 100, so 0 signals that no qualifying subarray exists.

Example 3

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

Explanation: Only the entire array sums to at least 4, so the shortest — and only — qualifying subarray is the whole thing.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^4
  • 1 <= target <= 10^9
  • Every element of nums is positive.

Loading editor…

Code execution is coming soon.