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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,4], k = 4
Output: 1
💡 Note: The subarray [4] has sum 4 which is ≥ 4, and length 1 is the shortest possible
Example 2 — Multiple Elements Needed
$ Input: nums = [2,1,2], k = 4
Output: 3
💡 Note: The subarray [2,1,2] has sum 5 ≥ 4, and we need all 3 elements to reach the target
Example 3 — No Valid Subarray
$ Input: nums = [1,2], k = 4
Output: -1
💡 Note: No subarray has sum ≥ 4, so we return -1

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Shortest Subarray with Sum at Least K INPUT nums array: 1 idx: 0 4 idx: 1 4 idx: 2 k = 4 Input Values nums = [1, 4, 4] k = 4 Find shortest subarray with sum >= k ALGORITHM STEPS 1 Prefix Sum Array Compute: [0,1,5,9] 2 Monotonic Deque Track increasing prefix 3 Sliding Window Check: prefix[j]-prefix[i]>=k 4 Find Minimum Track shortest length Iteration Details i=1: prefix[1]=1 < k i=2: prefix[2]=5 >= k 5-1=4 >= k, len=1 i=3: prefix[3]=9 >= k Found min length = 1 FINAL RESULT Shortest subarray found: [4] Single element at index 1 OR index 2 (both valid) Output: 1 Verification Sum of [4] = 4 4 >= k (4) ... OK Key Insight: Using a monotonic deque with prefix sums achieves O(n) time complexity. The deque maintains increasing prefix sums, allowing efficient lookup of valid subarrays. When prefix[j] - prefix[i] >= k, we found a candidate subarray of length (j - i) and pop i since shorter subarrays can't improve. TutorialsPoint - Shortest Subarray with Sum at Least K | Optimal Solution (Monotonic Deque)
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
78.4K Views
Medium Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen