Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray 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
nums
be empty?
nums
will always contain at least one positive integer.target
always be a positive integer?
target
is guaranteed to be positive.nums
be?
nums
when given in a real setting. Common constraints can be (10^5) or (10^6).We will use the sliding window/two-pointer technique for this problem. This involves maintaining a window defined by two pointers (left
and right
) that will efficiently find the minimal length subarray with the sum greater than or equal to target
.
left
starting at the beginning of the array, and right
iterating through the array.current_sum
to store the current subarray sum.min_length
to store the minimal length of valid subarrays. Set it initially to infinity (float('inf')
).right
over the array and add nums[right]
to current_sum
.current_sum
is greater than or equal to target
, try to shrink the window by moving left
to the right and updating current_sum
accordingly. Also, update min_length
with the smaller length found.min_length
is still infinity, no valid subarray was found. Return 0.min_length
.nums
. This is because each element is processed at most twice, once by right
and once by left
.Here’s the code implementing the above strategy:
def minSubArrayLen(target, nums):
left = 0
current_sum = 0
min_length = float('inf')
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= target:
min_length = min(min_length, right - left + 1)
current_sum -= nums[left]
left += 1
return 0 if min_length == float('inf') else min_length
# Example usage
print(minSubArrayLen(7, [2,3,1,2,4,3])) # Output: 2
print(minSubArrayLen(4, [1,4,4])) # Output: 1
print(minSubArrayLen(11, [1,1,1,1,1,1,1,1])) # Output: 0
This covers the entire solution including the problem statement, clarifying questions, detailed strategy, time complexity analysis, and the final implementation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?