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 ≥ KInput Array:140-10123Target: k = 4Found: subarray [4] has sum 4 ≥ 4Length = 1 (shortest possible)Output: 1Shortest subarray
Understanding the Visualization
1
Input
Array [1,4,0,-1] and target k=4
2
Process
Find shortest subarray with sum ≥ 4
3
Output
Return length 1 (subarray [4])
Key Takeaway
🎯 Key Insight: Use prefix sums with monotonic deque to efficiently track optimal starting positions for minimum length subarrays
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