medium +25 pts

Minimum Size Subarray Sum

Find the shortest contiguous subarray whose sum is at least a given target.

Implement the function `min_subarray_len(target, nums)` that takes a positive integer `target` and a list of positive integers `nums`. The function must return the minimal length of a contiguous subarray whose sum is at least `target`. If no such subarray exists, return `0`. **Details:** - `nums` elements are positive integers, so the sliding window technique is applicable. - The function should operate in O(n) time and O(1) extra space. - If `nums` is empty, return `0`. **Input:** - `target`: an integer, 1 <= target <= 10^9 - `nums`: a list of integers, each 1 <= nums[i] <= 10^4, length 0 <= len(nums) <= 10^5

Constraints

1 <= target <= 10^9 0 <= len(nums) <= 10^5 1 <= nums[i] <= 10^4 Expected O(n) time, O(1) space.

Example

>>> min_subarray_len(7, [2,3,1,2,4,3])
2
>>> min_subarray_len(4, [1,4,4])
1
>>> min_subarray_len(11, [1,1,1,1,1,1,1,1])
0
>>> min_subarray_len(15, [1,2,3,4,5])
5
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use two pointers to maintain a sliding window. Expand the right pointer to increase the sum, and when the sum is >= target, try to shrink the left pointer to find a shorter valid window.
Keep track of the minimum window length found so far. Start with a very large number (like float('inf')).
Remember to return 0 if no valid subarray was found.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.