MediumSliding Window
Minimum Size Subarray Sum
metagoogleamazonmicrosoftbloomberggoldman-sachs
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
A subarray is a contiguous non-empty sequence of elements within an array.
Examples
Example 1
Input
target = 7, nums = [2,3,1,2,4,3]
Output
2
The subarray [4,3] has sum 7 which is >= target, and its length 2 is the smallest possible.
Example 2
Input
target = 4, nums = [1,4,4]
Output
1
The single element [4] already meets the target of 4.
Example 3
Input
target = 11, nums = [1,1,1,1,1,1,1,1]
Output
0
The total sum of the array is 8 which is less than 11, so no valid subarray exists.
Constraints
- 1 <= target <= 109
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 104
Optimal complexity
Time
O(n)
Space
O(1)
One problem, two ways to prep
Choose between solo practice and interview simulation
Practice Mode keeps things simple with code + tests. AI Interview Mode adds voice, pressure, and a post-round score summary.