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.
The program calculates the prefix sum array and uses a deque to manage the indices of potential subarray starts. It iterates over each prefix sum. For each prefix sum, it checks if there's any prior prefix sum that's at least k
less than the current sum. If so, it updates the potential minimum length of the subarray. After finishing the loop, if result
is still INT_MAX
, it returns -1
as no valid subarray exists.
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.
1function shortestSubarray(nums, k) {
2 let minLength = Infinity;
3 for (let start = 0; start < nums.length; ++start) {
4 let sum = 0;
5 for (let end = start; end < nums.length; ++end) {
6 sum += nums[end];
7 if (sum >= k) {
8 minLength = Math.min(minLength, end - start + 1);
9 break;
10 }
11 }
12 }
13 return minLength === Infinity ? -1 : minLength;
14}
15
16let nums = [2, -1, 2];
17let k = 3;
18console.log(shortestSubarray(nums, k)); // Output: 3
Inside a nested loop structure, this JavaScript code iterates over every possible starting point for a subarray. It accumulates a running sum and updates the best length when the sum reaches or exceeds k
. The language's native handling of large numbers assists with practical limits but does not alleviate the inherent inefficiency.