Menu
CoddyTech

Minimum Size Subarray Sum

You get a positive integer target and an array nums of positive integers. Find the shortest subarray (a run of neighbouring elements) whose sum is at least target, and return its length. If no subarray reaches target, return 0.

Function

minSubArrayLen(target: integer, nums: integer-array) → integer
targetinteger
the sum a subarray must reach or pass
numsinteger-array
the array of positive integers
Returnsinteger
the length of the shortest subarray with sum at least target, or 0 if none exists

Constraints

  • 1 ≤ target ≤ 109
  • 1 ≤ nums.length ≤ 2 × 104
  • 1 ≤ nums[i] ≤ 104

Examples

Input
target = 15nums = [4, 2, 9, 3, 7, 1, 5]
Output
3
Explanation
No two neighbours reach 15: the largest pair is 9 + 3 = 12. Three do: 4 + 2 + 9 = 15 and 9 + 3 + 7 = 19, so the answer is 3.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

How would you solve it if nums could also hold zeros and negative numbers, where the sliding window no longer works?

Reset code
def minSubArrayLen(target, nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

target = 15
nums = [4, 2, 9, 3, 7, 1, 5]

Expected

3