Minimum Length Subarray with Sum Threshold
Stacks & QueuesAuto-graded · 24 test casesLast updated
Tests the ability to optimize subarray sum queries using prefix sums and monotonic deque when values can be negative.
You are given an array of integers values (which may include negative numbers) and an integer threshold.
Your task is to find the length of the shortest contiguous subarray whose sum is greater than or equal to threshold. If no such subarray exists, return -1.
A subarray must contain at least one element.
Constraints
1 <= len(values) <= 200,000-10^9 <= values[i] <= 10^9-10^9 <= threshold <= 10^9- The subarray must be non-empty
Examples
Example 1
Input: min_subarray_sum_threshold([2, -1, 2], 3)
Output: 3
Example 2
Input: min_subarray_sum_threshold([1, 2, 3, 4, 5], 11)
Output: 3
Example 3
Input: min_subarray_sum_threshold([1, 2], 4)
Output: -1
Example 4
Input: min_subarray_sum_threshold([-2, -1, 2, 1], 1)
Output: 1
Hints
Hint 1
Consider using cumulative sums to quickly compute subarray totals between any two positions.
Hint 2
A monotonic deque can help track promising starting positions while maintaining useful ordering properties.
Hint 3
Each position should enter and leave your data structure at most once to achieve linear time complexity.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to transform the subarray sum problem into a problem about pairs of cumulative sum positions. We build a cumulative sum array where cumulative[i] represents the sum of all elements before index i. Then any subarray from index i to j (exclusive) has sum equal to cumulative[j] - cumulative[i].
We need to find pairs (i, j) where cumulative[j] - cumulative[i] >= threshold that minimize j - i.
The challenge is that negative values prevent us from using a standard two-pointer sliding window, since extending or shrinking the window doesn't guarantee monotonic sum changes.
Instead, we use a monotonic deque to track candidate starting positions:
- Scan from left to right through cumulative sum positions
- At each position
j, check if any candidates in our deque form a valid subarray:- Pop from the front while the sum condition is satisfied
- Record the length and remove that candidate (it can't produce a better result later)
- Maintain monotonicity: Remove candidates from the back if they have cumulative sums greater than or equal to the current position (they're dominated by the current position for future queries)
- Add the current position to the deque
Why This Works
The algorithm is based on two pruning principles:
Front removal is safe: Once we find that position i forms a valid subarray ending at j, any future ending position j' > j paired with i produces a longer subarray. Position i has already yielded its optimal answer.
Back removal is safe: If position i has a cumulative sum greater than or equal to position j where i < j, then for any future position k > j:
- Position
jproduces a sum at least as large asi(sincecumulative[k] - cumulative[j] >= cumulative[k] - cumulative[i]) - Position
jyields a shorter subarray (k - j < k - i)
Therefore i is dominated and can never produce an optimal answer.
Because we maintain strict increasing order of cumulative sums in the deque, checking only the front element is sufficient—if it doesn't satisfy the threshold condition, no element in the deque will.
Complexity
Time: O(n) where n is the length of the input array. Each cumulative sum position is added to the deque exactly once and removed at most once, resulting in amortized constant work per element.
Space: O(n) for storing the cumulative sum array and the deque (which can hold at most n+1 positions).
Solution
from collections import deque
from typing import List
def min_subarray_sum_threshold(values: List[int], threshold: int) -> int:
cumulative = [0]
for val in values:
cumulative.append(cumulative[-1] + val)
min_length = len(values) + 1
queue = deque()
for right, cum_sum in enumerate(cumulative):
while queue and cum_sum - cumulative[queue[0]] >= threshold:
min_length = min(min_length, right - queue.popleft())
while queue and cumulative[queue[-1]] >= cum_sum:
queue.pop()
queue.append(right)
return -1 if min_length == len(values) + 1 else min_length