← All Exercises

Minimum Size Subarray Sum

intermediatepython~25min

Background

Minimum-window problems model bandwidth throttling, budget consumption, and resource windows over positive streams.

Problem

Given a positive integer target and an array of positive integers, return the length of the shortest contiguous subarray whose sum is at least target, or 0 if none exists.

Input

A positive integer target and a list of positive integers, with length up to 100000.

Output

The shortest qualifying length as an integer, or 0 when the total sum is below target.

Sample tests

Sample 1

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

Sample 2

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

Sample 3

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

Your solution

Learning objective

Apply the variable-size sliding window pattern with a monotonic sum and prove linear time.