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
๐ŸŽฏ Treasure Hunt VisualizationStart0 coins+2Total: 2-1Total: 1+2Total: 3 โ‰ฅ k!๐Ÿง  The Smart Strategy (Monotonic Deque)โ€ข Keep track of promising starting positions in orderโ€ข When we have enough coins, check shortest path from best starting pointโ€ข Remove bad starting points that will never be optimalโ€ข This ensures we always find the shortest successful treasure hunt!๐ŸŽฏ Result: Shortest path from Start to +2 position = 3 stepsArray: [2, -1, 2], k = 3 โ†’ Answer: 3We need all 3 elements to reach sum โ‰ฅ 3
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track current sum and minimum length

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -105 โ‰ค nums[i] โ‰ค 105
  • 1 โ‰ค k โ‰ค 109
  • Important: Array can contain negative numbers
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 25
48.2K Views
High Frequency
~25 min Avg. Time
1.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