Shortest Subarray with Sum at Least K - Problem
Given an integer array nums and an integer k, find the shortest contiguous subarray whose sum is at least k.
Your task is to return the length of this shortest subarray. If no such subarray exists, return -1.
Important: A subarray must be non-empty and consists of consecutive elements from the original array.
Example: For nums = [2, -1, 2] and k = 3, the subarray [2, -1, 2] has sum 3 and length 3, which is the shortest possible.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1], k = 1
โบ
Output:
1
๐ก Note:
The subarray [1] has sum 1 which equals k=1, so the shortest length is 1.
example_2.py โ With Negative Numbers
$
Input:
nums = [2, -1, 2], k = 3
โบ
Output:
3
๐ก Note:
The shortest subarray with sum โฅ 3 is [2, -1, 2] with sum 3 and length 3.
example_3.py โ No Valid Subarray
$
Input:
nums = [1, 2], k = 4
โบ
Output:
-1
๐ก Note:
No subarray has sum โฅ 4. Maximum possible sum is 1+2=3, which is less than k=4.
Visualization
Tap to expand
Understanding the Visualization
1
Track Your Progress
Keep a running total (prefix sum) of coins collected so far
2
Smart Checkpoints
Remember promising starting points using a special queue
3
Find Shortcuts
When you have enough coins, check if starting from an earlier checkpoint gives a shorter path
Key Takeaway
๐ฏ Key Insight: By maintaining a monotonic deque of prefix sum indices, we can efficiently find the shortest subarray ending at each position, achieving optimal O(n) time complexity even with negative numbers.
Time & Space Complexity
Time Complexity
O(nยฒ)
Nested loops: outer loop runs n times, inner loop runs up to n times
โ Quadratic Growth
Space Complexity
O(1)
Only using a few variables to track current sum and minimum length
โ Linear Space
Constraints
- 1 โค nums.length โค 105
- -105 โค nums[i] โค 105
- 1 โค k โค 109
- Important: Array can contain negative numbers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code