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.
Example 1:
Input: nums = [1], k = 1 Output: 1
Example 2:
Input: nums = [1,2], k = 4 Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3 Output: 3
Constraints:
1 <= nums.length <= 105-105 <= nums[i] <= 1051 <= k <= 109This 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.
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.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), for the prefix sum array and deque.
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.
This solution checks each subarray starting from every index. We accumulate the sum as we extend the subarray, and once we reach a sum that's at least k, we update our minimum length if this subarray is shorter than previously found subarrays. It's computationally intense and feasible only for small arrays.
C++
Java
Python
C#
JavaScript
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.
| Approach | Complexity |
|---|---|
| Prefix Sum and Sliding Window with Deque | Time Complexity: O(n), where n is the length of the array. |
| Brute Force Approach | Time Complexity: O(n^2), where n is the length of the array. |
Shortest Subarray with Sum at Least K | Leetcode 862 • Techdose • 39,723 views views
Watch 9 more video solutions →Practice Shortest Subarray with Sum at Least K with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor