Grow and repair a variable window
Distinguish longest-under-budget from shortest-reaching-target windows.
Understand the idea
For nonnegative values, extending a sum window cannot reduce its sum. To find the longest window with sum ≤ K, extend right, remove left values while over budget, then measure. To find the shortest window with sum ≥ S, measure each valid window before removing its left value.
Trace a small example
For [2, 1, 3, 2] and budget 4, the longest valid length is 2. For target 5, the shortest valid length is 2 from [3, 2]. The two tasks measure at different points: after repair for a maximum, before removal for a minimum.
Conditions and cost
Each pointer advances at most n times, giving O(n) total work. This sum-based rule needs nonnegative elements and, for the shortest nonempty formulation, S > 0. In [5, −4] with budget 1, discarding 5 too early would miss the valid length-2 window.
Prefix sum explorer
Query [l, r] is zero-based and inclusive. P[k] stores the total of the first k values; P[0] is zero.
Input array a
Prefix array P
Preprocess once in O(n). Each range sum then takes O(1).
Guided simulation · Change the inputs to test your understanding.
When should a shortest sum-at-least-target algorithm record a valid window?
Turn the idea into code
Find the shortest nonempty window with sum at least 7 in [2, 3, 1, 2, 4, 3].
Give me a hint
Keep shrinking while the sum remains sufficient.
Show the explained solution
The length-2 window [4, 3] reaches 7. No single element does, so 2 is optimal.
Your notes
Mark complete when you can explain it yourself.