Sponsored
Sponsored
This approach uses a prefix sum array to store cumulative sums and a deque to maintain the indices of suffix values. The deque is used to efficiently find the shortest subarray with the required sum condition. For each element, we calculate the prefix sum and determine the shortest subarray that satisfies the condition using the deque.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), for the prefix sum array and deque.
1function shortestSubarray(nums, k) {
2 let n = nums.length;
3 let prefixSum = new Array(n + 1).fill(0);
4 for (let i = 0; i < n; ++i) {
5 prefixSum[i + 1] = prefixSum[i] + nums[i];
6 }
7 let deque = [];
8 let result = Infinity;
9 for (let i = 0; i <= n; ++i) {
10 while (deque.length > 0 && prefixSum[i] - prefixSum[deque[0]] >= k) {
11 result = Math.min(result, i - deque.shift());
12 }
13 while (deque.length > 0 && prefixSum[i] <= prefixSum[deque[deque.length - 1]])
14 deque.pop();
15 deque.push(i);
16 }
17 return result === Infinity ? -1 : result;
18}
19
20let nums = [2, -1, 2];
21let k = 3;
22console.log(shortestSubarray(nums, k)); // Output: 3
The JavaScript solution utilizes an array to emulate a deque, keeping track of prefix sum indices as it checks potential subarrays for the sum condition. Each valid subarray found by comparing the current prefix sum against stored indices leads to an evaluation and possible reduction of the shortest subarray length.
Although a brute force approach will not be efficient for larger inputs, it's a good starting point to understand the combination of elements in this problem. We iterate over every starting point in the array and extend the subarray until the sum requirement is satisfied or the end of the array is reached. This ensures that we verify all possible subarray combinations.
Time Complexity: O(n^2), where n is the length of the array.
Space Complexity: O(1), since we're not using additional data structures.
This brute force Java approach attempts every subarray possible from each index, adding elements one by one until the subarray sum is at least k
. While thorough, its O(n^2) complexity means this method is mainly of educational value for understanding subarray dynamics under specific conditions.