Shortest Subarray with Sum at Least K: Prefix Sums, Negative Numbers, and a Monotonic Deque
Quick Overview
Explain why a positive-only shrinking window fails with negative values, then derive the prefix-boundary frontier for shortest subarray sum at least K. Follow an original deque trace, prove front retirement and back domination, and run Python code checked against raw-interval enumeration on 117,186 finite cases. Includes target-range caveats and five related PracHub exercises.
For Shortest Subarray with Sum at Least K, negative numbers invalidate the usual shrinking-sum window. Use prefix sums and keep candidate starting boundaries in a monotonic deque. Remove feasible starts from the front after recording their lengths, and remove dominated starts from the back when a later boundary has a smaller or equal prefix sum.
Name which end removes a feasible start and which end removes a dominated future start. A front candidate has already achieved its shortest useful endpoint. A back candidate is permanently worse than a newer candidate for every future endpoint. Explaining both is more valuable than recognizing a familiar deque template.
Try Find shortest subarray meeting target sum before reading the implementation. Its generalized contract permits negative values and requires a nonempty interval. Confirm the target range and no-answer value rather than importing conventions from a positive-only window exercise.
Evidence boundary: official problem and Python behavior are linked where used. The counterexamples, prefix trace, proofs, code, and brute-force checks are original teaching work. Observed checks ran under Python 3.12.14. They do not establish any employer's interview process, question frequency, or hiring outcome; no candidate reports are used.

Why a positive-only shrinking window fails
Official contract: LeetCode 862 requests the shortest nonempty contiguous subarray with sum at least K, returning −1 when none exists. Its values may be negative, while its target is positive. The algorithm below also defines empty-input and nonpositive-target behavior explicitly.
For nonnegative numbers, extending a window cannot lower its sum, and removing its leftmost element cannot increase the sum. Those facts justify advancing the left boundary while the window remains valid. They are properties of the inputs, not consequences of using two pointers.
Now take [1,-1,5] with K=5. The ordinary loop first finds total 5 across all three elements and records length 3. It removes the first 1, leaving total 4, and stops shrinking. Removing the next element, −1, would increase the sum back to 5 and reveal the optimal singleton [5], but that loop never reaches it.
The optimal interval is nums[2:3]=[5], so its length is 1; the shrinking-window baseline returns 3. A fixed-size window can still track sums containing negatives; the failure concerns this variable-size threshold proof. The existing prefix-sum guide develops exact-sum lookup, while the inequality here needs a different candidate structure.
Turn each interval into two prefix boundaries
Define P[0]=0 and P[i] as the sum of the first i elements. The half-open interval nums[j:i] has sum P[i]−P[j] and length i−j. We need j<i and P[i]−P[j]≥K, then minimize i−j across valid pairs.
The initial zero represents an interval starting at element zero. It is a real candidate boundary, not an extra array value. Without it, a singleton that already meets the target can be missed. Likewise, prefix index i points after element i−1; confusing boundary indices with element positions introduces an unnecessary plus-one error.
For the original array, the prefixes are [0,1,0,5]. They are not sorted, because the −1 lowers the cumulative total. A simple binary search over the original prefix array therefore has no ordered-input guarantee. We will instead maintain an ordered subset of useful earlier boundaries.
Prove which candidates can leave the back
Suppose j<i and P[i]≤P[j]. For any future endpoint t>i, P[t]−P[i] is at least P[t]−P[j]. Starting at i is therefore at least as easy to make feasible, and t−i is strictly shorter than t−j. If j works for a future endpoint, i also works and produces a strictly shorter interval.
That is permanent domination, so remove j from the back. Continue removing while the new prefix is no greater than the last retained prefix. After appending the new index, candidate indices increase and their prefix values strictly increase. These are two separate invariants: index order gives temporal validity, while prefix order makes useful front checks possible.
Equality matters to the explanation. If two prefixes have the same value, the later boundary gives the same future sum with a shorter interval. Keeping the newer one is sufficient. A variant that retains equal prefixes can still be correct with different invariants; using <= here deliberately removes that redundant older candidate.
Prove which candidates can leave the front
At endpoint i, if P[i]−P[front]≥K, record the interval length before removing that front. Endpoints are processed in increasing order. Every later endpoint paired with this same start would have a larger length, so keeping that start cannot improve the answer already recorded from it.
Continue while the next front is also feasible. The later start may give a shorter interval ending at the same i. With [1,2] and K=2, the final prefix makes both starts feasible: recording the whole array gives length 2, but the second front gives the singleton length 1. With one if, the function can finish at length 2 while the last element alone already meets the target.
Because retained prefix values increase, once the front is infeasible, every later candidate is also infeasible at this endpoint. That lets the front loop stop without scanning the rest. Combined with the back-domination proof, the deque retains precisely the candidate information still needed for future improvements; it does not represent every historical prefix.
Trace the two removal rules on one small array
The notation index:prefix identifies a boundary and its cumulative value. The deque column shows its state after both removal loops and the append.
| i | P[i] | Action | Deque afterward | Best length |
|---|---|---|---|---|
| 0 | 0 | Add initial boundary | [0:0] | No answer |
| 1 | 1 | No feasible front; no domination | [0:0, 1:1] | No answer |
| 2 | 0 | Remove 1:1 and older equal 0:0 from back | [2:0] | No answer |
| 3 | 5 | Record 3−2=1; retire front 2:0 | [3:5] | 1 |
At i=2, neither removed boundary had met the positive target. They leave because the new boundary is better for future endpoints. At i=3, boundary 2 leaves for the other reason: its best possible useful endpoint has now been recorded. Do not describe both operations as “removing expired elements”; there is no fixed window width here.

Implement the candidate frontier with explicit boundaries
The implementation does not modify nums. It assumes an integer sequence and target rather than validating untrusted objects. Returning −1 for empty input is a documented extension; with a nonpositive target, it still requires a nonempty interval.
from collections import deque
def shortest_subarray(nums, k):
prefix = [0]
for value in nums:
prefix.append(prefix[-1] + value)
candidates = deque()
best = len(nums) + 1
for right, total in enumerate(prefix):
while candidates and total - prefix[candidates[0]] >= k:
best = min(best, right - candidates.popleft())
while candidates and total <= prefix[candidates[-1]]:
candidates.pop()
candidates.append(right)
return best if best <= len(nums) else -1
Python documentation: collections.deque supports approximately constant-time append and pop operations at both ends. Using a list and repeatedly deleting its first element introduces movement of the remaining entries. The data structure supports the bound, while the two proofs establish which entries may be removed.
The current boundary is appended after checking earlier starts, so it cannot create a zero-length answer against itself. Feasibility is checked before back domination in this version. That ordering also handles the generalized K≤0 contract: for [0], K=0, the earlier zero prefix must yield length 1 before the equal newer prefix replaces it.
For the official positive-target case, some alternative loop orderings can be equivalent because a dominated prefix cannot simultaneously give a positive sum at the current boundary. State the assumptions behind a variation rather than claiming there is only one correct ordering. The shown ordering keeps the generalized nonempty contract straightforward.
Test the result against actual interval sums
An independent oracle can enumerate all start and end positions and accumulate the raw array values. It does not inspect the optimized prefix array or reuse the deque rules. That independence matters: a test built from the same mistaken boundary formula can agree with a broken implementation.
Save the first block as solution.py, then place the following complete checking block beside it and run it with Python. The small finite universe exercises repeated prefixes, negative dips, equality at the target, and no-answer inputs.
from itertools import product
from solution import shortest_subarray
import json
import platform
def brute(nums, k):
best = len(nums) + 1
for left in range(len(nums)):
total = 0
for right in range(left, len(nums)):
total += nums[right]
if total >= k:
best = min(best, right - left + 1)
return best if best <= len(nums) else -1
checked = 0
for size in range(7):
for values in product(range(-2, 3), repeat=size):
for k in range(1, 7):
nums = list(values)
before = nums[:]
assert shortest_subarray(nums, k) == brute(nums, k)
assert nums == before
checked += 1
named = [([1, -1, 5], 5, 1), ([1, 2], 2, 1),
([2, 1, -4, 5], 4, 1), ([6], 5, 1),
([-4, -2], 1, -1), ([0, 0], 1, -1),
([1, 0, 0], 1, 1), ([2**40], 2**40, 1)]
extensions = [([], 0, -1), ([0], 0, 1), ([-3], -2, -1)]
for nums, k, expected in named + extensions:
assert shortest_subarray(nums, k) == brute(nums, k) == expected
print(json.dumps({'python': platform.python_version(), 'exhaustive_cases': checked,
'array_lengths': [0, 6], 'values': [-2, -1, 0, 1, 2],
'positive_targets': [1, 6], 'named_cases': len(named),
'nonpositive_target_extensions': len(extensions)}, sort_keys=True))
Observed local result: the exact published function and checking script agreed in all 117,186 combinations of lengths 0–6, values drawn from −2 through 2, and targets 1–6. Eight additional named cases and three nonpositive-target extension cases passed. Each generated case also checked that the input stayed unchanged.
Those are finite correctness checks, not a large-array benchmark or a replacement for the domination proof. The named cases include [2,1,-4,5], K=4: its negative dip must remove several back candidates. If that back loop becomes a single if, a larger prefix can remain ahead of a better start and hide the optimal singleton later.
Its prefixes are [0,2,3,-1,4]. At the −1 prefix, all three earlier candidates are dominated. Removing only the last one leaves prefix 2 ahead of prefix −1. At the final endpoint, the front loop can stop at that infeasible prefix 2 before reaching the valid later start with prefix −1. The two while loops therefore maintain the structure needed by each other's stopping rule; they are not merely a faster way to repeat optional cleanup.
Distinguish an inequality from exact-sum hashing
For an exact-sum query, P[i]−P[j]=K becomes the lookup P[j]=P[i]−K. A hash map can store counts, earliest positions, or latest positions depending on the requested output. The condition in this problem instead permits every prior prefix no greater than P[i]−K.
With [6] and K=5, the answer is 1 although no interval sums to exactly 5. Looking only for a prefix equal to P[i]−K misses this valid interval. A threshold query needs reasoning about an ordered range of possible prefix values, not a change to which payload an exact-match map stores.
The objective also controls domination. For shortest intervals, a later start with a no-larger prefix is preferable. That same removal is not automatically valid for a longest-interval question. Similarly, a range condition involving maximum minus minimum needs information about element extrema, not cumulative sums. Read “sum,” “range,” “shortest,” and “longest” as parts of the contract.
Explain amortized cost and numeric range honestly
There are n+1 prefix boundaries. Each is appended once and can be removed at most once in total, from either end. An individual iteration may remove many candidates, but the combined removals across the run are linear. This gives O(n) time under bounded-integer arithmetic assumptions and O(n) additional space for prefixes and the frontier.
The official bounds allow prefix magnitudes around 10¹⁰, which exceed signed 32-bit range. Use an appropriately wide accumulator in fixed-width languages. Python integers have arbitrary precision, but that is not a promise that arithmetic on unrestricted-size integers has constant bit cost.
A streaming adaptation can store index/prefix pairs directly in the deque instead of retaining the full prefix array. Its worst-case candidate storage is still linear. Do not call it constant space merely because it processes incoming values in order. Once length 1 is found, an optional early return is safe for this nonempty shortest-length output.
Practice the condition and objective together
These PracHub records are related practice rather than predictions of an interview. Before adapting the code, name the new objective and the condition that makes an interval valid.
| Complete practice question | What to distinguish |
|---|---|
| Find shortest subarray meeting target sum | At-least sum, negative values, and nonempty boundaries |
| Count Subarrays with a Target Sum | Exact-sum equality and count payloads |
| Length of the Longest Contiguous Subarray Summing to a Target | Longest exact sum and the choice of stored index |
| Maximum Subarray Sum with a Length Cap | A different objective with an explicit age limit on starts |
| Find shortest subarray with range ≥ k | Max-minus-min range instead of a sum threshold |
Return to Find shortest subarray meeting target sum, trace [1,-1,5], and label every removal as either a recorded feasible start or a dominated future start. Then replace each while with if separately and predict the first wrong length before rerunning the checks. That checks the reasoning that survives a changed input, rather than just the order of deque calls.
Comments (0)