15% off all plans & roadmaps Use code
See plansLeetCode 862 · Solution & editorial
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.
Shortest Subarray with Sum at Least K is a Sliding Window problem, in the Monotonic Queue for Max/Min subpattern. The pattern covers fixed-size, variable-size, and character frequency matching window techniques
Master monotonic queue (deque) to find maximum or minimum in sliding windows efficiently in O(n) time.
The reference solution runs in O(n) time and O(n) space.
Shortest Subarray with Sum at Least K has been reported in interviews at Goldman Sachs.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Shortest Subarray with Sum at Least K is a Sliding Window problem, in the Monotonic Queue for Max/Min subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.