Shortest Subarray with Sum at Least K
Problem Statement
This one is rated Hard on LeetCode, and it is the trap question of this sub-pattern.
You are given an integer array nums (it can contain negative numbers) and a number k.
Find the shortest non-empty contiguous subarray whose sum is at least k. Return its length. If no such subarray exists, return -1.
An integer array nums of length n (values may be negative), and an integer k.
A single number: the length of the shortest subarray with sum ≥ k, or -1 if there is none.
The only subarray is [1], and its sum 1 is at least 1.
The biggest possible sum is 1 + 2 = 3, which is less than 4.
Only the whole array reaches 3. Note that the −1 sits in the middle and can't be skipped.
[32, 40, 95] sums to exactly 167. The usual "shrink while sum ≥ k" window returns 5 here — see the trap visual.
- • 1 ≤ n ≤ 10^5
- • −10^5 ≤ nums[i] ≤ 10^5
- • 1 ≤ k ≤ 10^9
- • Prefix sums can reach 10^10 in size — use a 64-bit type.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Build prefix sums, then try every (start, end) pair
Drop starts that a later start beats; binary search the rest for each end
Deque of starts with increasing P; pop front when it reaches k, pop back when beaten
Build the prefix sum array P. Every subarray nums[i … j−1] has sum P[j] − P[i]. Try every pair i < j, and keep the smallest j − i whose sum is at least k.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.