Shortest subarray length
January 9, 2024
Problem #
Given an array of integers nums
and a target value k
, find the length of the shortest subarray whose sum is greater than or equal to k
.
Solution #
Steps:
- Initialize two pointers,
left
andright
, both at the beginning of the array. - Initialize a variable
current_sum
to 0. - Iterate while
right
is within the bounds of the array:- Add
nums[right]
tocurrent_sum
. - While
current_sum
is greater than or equal tok
:- Update the minimum length if needed:
min_length = min(min_length, right - left + 1)
. - Subtract
nums[left]
fromcurrent_sum
. - Move
left
to the right.
- Update the minimum length if needed:
- Move
right
to the right.
- Add
- Return
min_length
(or a large value if no subarray meets the criteria).
Time Complexity #
O(n), where n is the length of the array.
Space Complexity #
O(1), as we only use a constant amount of extra space.
Example #
def shortest_subarray_with_sum(nums, k):
min_length = float('inf')
current_sum = 0
left = 0
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= k:
min_length = min(min_length, right - left + 1)
current_sum -= nums[left]
left += 1
return min_length if min_length != float('inf') else -1