Shortest Subarray with Sum at Least K — LeetCode 862 Python Solution
HardQueueArrayBinary SearchPrefix SumSliding WindowMonotonic QueueHeap (Priority Queue)
- Problem
- #862
- Pattern
- Sliding Window
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
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
LeetCode 2398Maximum Number of Robots Within BudgetHardLeetCode 209Minimum Size Subarray SumMediumLeetCode 713Subarray Product Less Than KMediumLeetCode 1004Max Consecutive Ones IIIMediumLeetCode 2106Maximum Fruits Harvested After at Most K StepsHardLeetCode 2302Count Subarrays With Score Less Than KHard
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.