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.
For example:
target = 7, nums = [2,3,1,2,4,3]
The correct output is 2
because the subarray [4,3]
has the minimal length under the problem constraint.
Another example:
target = 4, nums = [1,4,4]
The correct output is 1
.
And one last example:
target = 11, nums = [1,1,1,1,1,1,1,1]
The correct output is 0
because there is no subarray whose sum is greater than or equal to 11
.
Constraints:
1 <= target <= 10^9
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^4
Can you provide an efficient algorithm to solve this problem, considering both time and space complexity?
A naive approach would be to iterate through all possible subarrays and check if their sum is greater than or equal to the target. We keep track of the minimum length found so far.
min_length
to infinity.i
from 0 to n-1
.i
, iterate through all possible end indices j
from i
to n-1
.nums[i:j+1]
.min_length
with the minimum of min_length
and j - i + 1
.min_length
is still infinity, return 0. Otherwise, return min_length
.def min_subarray_len_brute_force(target: int, nums: list[int]) -> int:
n = len(nums)
min_length = float('inf')
for i in range(n):
for j in range(i, n):
sub_array_sum = sum(nums[i:j+1])
if sub_array_sum >= target:
min_length = min(min_length, j - i + 1)
return min_length if min_length != float('inf') else 0
The time complexity of this approach is O(n^2) because we have nested loops to iterate through all possible subarrays.
The space complexity is O(1) because we only use a constant amount of extra space.
A more efficient approach is to use the sliding window technique. This allows us to find the minimum length subarray in O(n) time.
min_length
to infinity.window_start
to 0 and window_sum
to 0.window_end
from 0 to n-1
.nums[window_end]
to window_sum
.window_sum
is greater than or equal to the target:
a. Update min_length
with the minimum of min_length
and window_end - window_start + 1
.
b. Subtract nums[window_start]
from window_sum
.
c. Increment window_start
.min_length
is still infinity, return 0. Otherwise, return min_length
.def min_subarray_len_optimal(target: int, nums: list[int]) -> int:
n = len(nums)
min_length = float('inf')
window_start = 0
window_sum = 0
for window_end in range(n):
window_sum += nums[window_end]
while window_sum >= target:
min_length = min(min_length, window_end - window_start + 1)
window_sum -= nums[window_start]
window_start += 1
return min_length if min_length != float('inf') else 0
The time complexity of this approach is O(n) because we iterate through the array at most twice (once with window_end
and once with window_start
).
The space complexity is O(1) because we only use a constant amount of extra space.