209. Minimum Size Subarray Sum
Asked at 15Bloomberg55Microsoft49Amazon49Meta48Google46Apple22TikTok53Citigroup81HCL60DoorDash51Oracle41Infosys39Yandex28tcs27Goldman Sachs21
Problem
Given positive integers nums, return the minimal length of a contiguous subarray whose sum is at least target, or 0 if none exists.
Example: target = 7, nums = [2,3,1,2,4,3] → 2 ([4,3])
Constraints: n ≤ 10⁵. Follow-up: also an O(n log n) solution.
All positive → expand r, and while sum ≥ target record the length and shrink from l.
Complexity: O(n) time, O(1) space.
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
l = s = 0
best = float("inf")
for r, x in enumerate(nums):
s += x
while s >= target:
best = min(best, r - l + 1)
s -= nums[l]
l += 1
return 0 if best == float("inf") else best
assert Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]) == 2
assert Solution().minSubArrayLen(11, [1, 1, 1, 1, 1, 1, 1, 1]) == 0
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int l = 0, s = 0, best = Integer.MAX_VALUE;
for (int r = 0; r < nums.length; r++) {
s += nums[r];
while (s >= target) {
best = Math.min(best, r - l + 1);
s -= nums[l++];
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
}
func minSubArrayLen(target int, nums []int) int {
l, s, best := 0, 0, math.MaxInt
for r, x := range nums {
s += x
for s >= target {
best = min(best, r-l+1)
s -= nums[l]
l++
}
}
if best == math.MaxInt {
return 0
}
return best
}