LeetCode209 Minimum Size Subarray Sum
Author: Stefan Su
Create time: 2022-10-26 23:51:34
Location: New York City, NY, USA
Description Medium
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray [nums[l], nums[l+1], ..., nums[r-1], nums[r]]
of which the sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
Example 1
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Constrains
1 <= target <= 10^9
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^4
Analysis
Using two indices to consider the sliced array and check the sum of this subarray with target
. If sum < target
, then move the right
index ahead to next position. But if not, use while
loop to move the left
index ahead to next position and subtract the previous value from the sum
, until sum < target
again. In this way, we can squeeze the length of subarray to the minimum one.
Solution
- Version 1: Slicing Window
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
"""
The code below is about min length of subarray
which sum is exactly equal to the target
"""
"""The code below is slicing window"""
if nums == None or len(nums) == 0 or sum(nums) < target:
return 0
if sum(nums) == target:
return len(nums)
result = len(nums)
left = 0
total = 0
for right in range(len(nums)):
total += nums[right]
while total >= target:
result = min(result, right - left + 1)
total -= nums[left]
left += 1
return result
Advance
When I was solving this problem, I incorrectly saw the condition as equal to target
. Therefore, the code below is the case when the sum of subarray is exactly equal to target
.
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
"""
The code below is about min length of subarray
which sum is exactly equal to the target
"""
length = 0
slow = 0
fast = 0
while fast <= len(nums):
temp = sum(nums[slow: fast])
if temp < target:
fast += 1
elif temp > target:
slow += 1
else:
curr_length = fast - slow
if length == 0 and curr_length != 0:
length = curr_length
if curr_length < length:
length = curr_length
fast += 1
slow += 1
return length
Hopefully, this blog can inspire you when solving LeetCode209. For any questions, please comment below.