Given an integer array nums
and an integer k
, return the length of the shortest non-empty subarray of nums
with a sum of at least k
. If there is no such subarray, return -1
.
A subarray is a contiguous part of an array.
For example:
nums = [1], k = 1
. The output should be 1
because the subarray [1]
has a sum of 1, which is at least k=1, and the length is 1.nums = [1, 2], k = 4
. The output should be -1
because no subarray has a sum of at least 4.nums = [2, -1, 2], k = 3
. The output should be 3
because the shortest subarray with a sum of at least 3 is the entire array [2, -1, 2]
, which has a length of 3.Write a function to efficiently find the length of the shortest subarray with a sum of at least k
.
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for finding the shortest part of a collection of numbers that adds up to at least a certain target value is simple. We look at every possible part, check if it meets the criteria, and remember the smallest one that does. We explore all options without trying to be smart about it.
Here's how the algorithm would work step-by-step:
def shortest_subarray_with_sum_at_least_k_brute_force(numbers, target):
minimum_length = float('inf')
# Iterate through all possible start indices
for start_index in range(len(numbers)):
current_sum = 0
# Iterate through all possible end indices starting from the start index
for end_index in range(start_index, len(numbers)):
current_sum += numbers[end_index]
# Check if the current subarray sum meets the target
if current_sum >= target:
#Update min length if current subarray is shorter
subarray_length = end_index - start_index + 1
minimum_length = min(minimum_length, subarray_length)
# If no subarray meets the target, return -1
if minimum_length == float('inf'):
return -1
return minimum_length
We want to find the shortest continuous section that adds up to at least a certain number. The trick is to keep track of possible starting points for our section using a special list that helps us quickly find the best start.
Here's how the algorithm would work step-by-step:
def shortest_subarray_with_sum_at_least_k(numbers, k_value):
prefix_sums = [0] * (len(numbers) + 1)
for i in range(len(numbers)):
prefix_sums[i+1] = prefix_sums[i] + numbers[i]
shortest_length = float('inf')
monotonic_queue = []
for i in range(len(prefix_sums)):
# Check for valid subarrays, removing from the front if possible
while monotonic_queue and prefix_sums[i] - prefix_sums[monotonic_queue[0]] >= k_value:
shortest_length = min(shortest_length, i - monotonic_queue[0])
monotonic_queue.pop(0)
# Maintain a decreasing prefix sum queue
while monotonic_queue and prefix_sums[monotonic_queue[-1]] >= prefix_sums[i]:
monotonic_queue.pop()
monotonic_queue.append(i)
if shortest_length == float('inf'):
return -1
return shortest_length
Case | How to Handle |
---|---|
Empty input array (nums is null or has length 0) | Return -1 immediately, as there's no subarray to evaluate. |
Array with one element, where the element is >= k | Return 1, as a single element subarray satisfies the condition. |
Array with one element, where the element is < k | Return -1, as no subarray can satisfy the condition. |
Array contains only negative numbers, and the sum of all elements is < k | Return -1, as no positive sum can be achieved. |
Array contains a mix of positive and negative numbers, with a very large negative number that drastically reduces the running sum | The sliding window or prefix sum approach will correctly handle large negative numbers by shrinking the window or discarding prefixes that reduce the sum below a certain threshold. |
All elements in the array are zero, and k > 0 | Return -1, as no positive sum can be achieved. |
All elements in the array are zero, and k <= 0 | Return 1, as a single zero element subarray satisfies the condition. |
Integer overflow in prefix sum calculation when nums contains large positive numbers and the array is large | Use long data type for prefix sums to prevent overflow. |