Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Prefix sum + Monotonic queue
- Prefix Sum and Monotonic Queue:
- We use a prefix sum array to keep track of cumulative sums.
- A deque (double-ended queue) is used to maintain indices of the prefix sum array in increasing order.
- For each index
i
, while there are indices in the deque and the prefix sum difference between the current index and the front of the deque is at leastK
, we update the minimum length. - We maintain the deque such that it helps to find the smallest subarray with the required sum efficiently.
- Steps:
- Initialise a deque and the prefix sum array.
- Traverse the prefix sum array.
- For each element, ensure that the elements in the deque are increasing.
- Calculate the potential minimum length whenever the required sum condition is met.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
because each element is processed at most twice (once added and once removed from the deque). - 🧺 Space complexity:
O(n)
, due to the extra space used for the prefix sum array and the deque.