Skip to content
RED SAGSkills

Shortest Window Reaching a Total

Given an array of positive integers nums and a positive integer total, return the length of the shortest contiguous subarray whose sum is at least total. If no such subarray exists, return 0.

Example 1

Input: total = 7, nums = [2, 3, 1, 2, 4, 3]
Output: 2
Explanation: [4, 3] sums to 7.

Example 2

Input: total = 20, nums = [1, 2, 3]
Output: 0

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^4
  • 1 <= total <= 10^9
Hint 1

All values are positive, so growing the window only increases the sum.

Hint 2

Extend the right edge, then shrink from the left while the sum is still large enough.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Game Developer, Automation Test Engineer, Data Engineer, Site Reliability Engineer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.