LeetCode 862: Shortest Subarray with Sum at Least K
Problem Description
Explanation:
To solve this problem, we can use a deque (double-ended queue) to maintain a monotonic increasing prefix sum array. We iterate over the input array nums
, compute the prefix sums, and store them along with their corresponding indices in the deque. At each step, we check if the current prefix sum minus the smallest prefix sum in the deque is greater than or equal to k
. If it is, we update the minimum length of subarray found so far. If not, we continue iterating and updating the deque.
Algorithm:
- Initialize variables:
n
as the length ofnums
,minLen
to store the minimum subarray length found so far (initially set ton + 1
),prefixSum
array to store the prefix sums, and a dequedeq
to maintain a monotonic increasing prefix sum array. - Initialize the deque
deq
with a tuple(0, -1)
to represent the initial prefix sum of 0 at index -1. - Iterate over the input array
nums
and compute the prefix sums, storing each prefix sum and its index in the deque. - At each step, check if the current prefix sum minus the smallest prefix sum in the deque is greater than or equal to
k
. - If yes, update
minLen
with the minimum length of subarray found so far. - If not, continue iterating and updating the deque.
- Return
minLen
if a valid subarray is found; otherwise, return -1.
Time Complexity:
The time complexity of this algorithm is O(n) where n is the length of the input array nums
.
Space Complexity:
The space complexity of this algorithm is O(n) to store the prefix sum array and the deque.
:
Solutions
class Solution {
public int shortestSubarray(int[] nums, int k) {
int n = nums.length;
int minLen = n + 1;
int[] prefixSum = new int[n + 1];
Deque<Integer> deq = new LinkedList<>();
deq.addLast(0);
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + nums[i];
while (!deq.isEmpty() && prefixSum[i + 1] - prefixSum[deq.peekFirst()] >= k) {
minLen = Math.min(minLen, i - deq.pollFirst() + 1);
}
while (!deq.isEmpty() && prefixSum[i + 1] <= prefixSum[deq.peekLast()]) {
deq.pollLast();
}
deq.addLast(i + 1);
}
return minLen == n + 1 ? -1 : minLen;
}
}
Related LeetCode Problems
Loading editor...