Shortest Subarray with Sum at Least K — LeetCode 862 Python Solution

HardQueueArrayBinary SearchPrefix SumSliding WindowMonotonic QueueHeap (Priority Queue)
Problem
#862
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview