HardNo. 0862
Shortest Subarray with Sum at Least K — LeetCode 862 Python Solution
- Pattern
- Sliding Window
- Topics
- Queue, Array, Binary Search, Prefix Sum, Sliding Window, Monotonic Queue, Heap (Priority Queue)
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [1], k = 1
- Output
- 1
Python solution
class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
s = list(accumulate(nums, initial=0))
q = deque()
ans = inf
for i, v in enumerate(s):
while q and v - s[q[0]] >= k:
ans = min(ans, i - q.popleft())
while q and s[q[-1]] >= v:
q.pop()
q.append(i)
return -1 if ans == inf else ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 862. Shortest Subarray with Sum at Least K is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2398 | Maximum Number of Robots Within Budget | Hard |
| 0209 | Minimum Size Subarray Sum | Medium |
| 0713 | Subarray Product Less Than K | Medium |
| 1004 | Max Consecutive Ones III | Medium |
| 2106 | Maximum Fruits Harvested After at Most K Steps | Hard |
| 2302 | Count Subarrays With Score Less Than K | Hard |
Frequently asked questions
- How hard is LeetCode 862. Shortest Subarray with Sum at Least K?
LeetCode 862. Shortest Subarray with Sum at Least K is rated Hard on LeetCode.
- What topics does LeetCode 862. Shortest Subarray with Sum at Least K cover?
LeetCode 862. Shortest Subarray with Sum at Least K is tagged Queue, Array, Binary Search, Prefix Sum, Sliding Window, Monotonic Queue and Heap (Priority Queue) on LeetCode.