DSA Factory
Free Arrays lessonsArrays · Stage 8 · Sliding window · Step 3

Grow, then shrink

A window that stretches on the right and tightens on the left. About 10 minutes.

A window that stretches and shrinks

You're saving up for a phone and want the shortest run of consecutive days whose earnings add up to at least the price. The window no longer has a fixed size.

Keep a left end and a right end. Move the right end forward one day at a time, adding each day in. As soon as the total reaches the target, you've found a candidate. Note its length.

Grow on the right: until the total is big enough.
target = 7
2
0
3
1
1
2
2
3
4
4
3
5
leftright

Grow to 2 + 3 + 1 + 2 = 8 ≥ 7. Length 4.

Move 1 of 6

Then squeeze from the left

Once the window is big enough, try to make it shorter. Drop the leftmost day and check again. Keep squeezing, noting each length, until the total falls below the target. Then go back to growing.

This only works because every number is positive: dropping a day can only lower the total. With negative numbers, dropping one could raise it, and the logic breaks.

Still big enough? note the length, then drop from the left.
Positive numbers only: negatives break the squeeze.
In code
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
    total += x
    while total >= target:
        best = min(best, right - left + 1)
        total -= nums[left]
        left += 1
return 0 if best == float("inf") else best
Quick check

The target is 10. The window holds 4, 3, 5, a total of 12. What happens next?

  1. ANote length 3, then drop the 4
  2. BAdd the next number
  3. CDrop the 5
Show the answer

Note length 3, then drop the 4. It's big enough, so note it, then try shorter by dropping from the left.

Your problem

Shortest window reaching a sum

You get a list of positive whole numbers and a target. Return the length of the shortest run of consecutive numbers whose sum is at least the target, or 0 if there is none.

Example
nums = [2, 3, 1, 2, 4, 3], target = 7 → 2

0 ≤ n ≤ 1,000,000 · 1 ≤ each value ≤ 10^6 · 1 ≤ target ≤ 10^9

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve