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]
should return 2
because the subarray [4,3]
has the minimal length under the problem constraint.
target = 4, nums = [1,4,4]
should return 1
.
target = 11, nums = [1,1,1,1,1,1,1,1]
should return 0
.
Describe the Brute Force solution to this problem. What is the Big O time and space complexity? Can you provide example code? Describe an optimal solution to this problem. What is the Big O time and space complexity? Can you provide example code? What edge cases should be considered?
A naive solution would involve checking every possible subarray and finding the minimum length that satisfies the condition. This involves two nested loops. The outer loop iterates through all possible start indices, and the inner loop iterates through all possible end indices from the current start index.
def min_subarray_len_brute_force(target, nums):
min_len = float('inf')
for i in range(len(nums)):
current_sum = 0
for j in range(i, len(nums)):
current_sum += nums[j]
if current_sum >= target:
min_len = min(min_len, j - i + 1)
break
return min_len if min_len != float('inf') else 0
O(n^2), where n is the length of the input array nums
, due to the nested loops.
O(1), as it uses only a constant amount of extra space.
A more efficient approach involves using the sliding window technique. We maintain a window defined by two pointers, left
and right
. We expand the window by moving the right
pointer until the sum of elements within the window is greater than or equal to the target. Once this condition is met, we try to shrink the window from the left
side to find the minimal length.
def min_subarray_len_sliding_window(target, nums):
left = 0
current_sum = 0
min_len = float('inf')
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= target:
min_len = min(min_len, right - left + 1)
current_sum -= nums[left]
left += 1
return min_len if min_len != float('inf') else 0
O(n), where n is the length of the input array nums
. Each element is visited at most twice (once by the right
pointer and once by the left
pointer).
O(1), as it uses only a constant amount of extra space.
nums
is empty, the function should return 0.