DSA Tracker

Visualize

Minimum Size Subarray Sum

Grow right, shrink left while still valid

time O(n)space O(1)

Growing the window blindly would work but re-scanning from scratch each time is wasteful. Instead, keep a running sum: expand the window by moving r right, and the moment the sum meets the target, shrink from the left as far as possible while it still qualifies — every shrink is a candidate for a new minimum length. This way each element is added once and removed once, so the whole scan stays O(n).

Details

Animated on: nums = [2,3,1,2,4,3], target = 7 — find the smallest contiguous subarray with sum >= target.

Problem:Minimum Size Subarray SumMedium

Pattern:Sliding Window

Grow right, shrink left while still valid

step 1 / 12

2
[0]
3
[1]
1
[2]
2
[3]
4
[4]
3
[5]

Grow the window by adding nums[0]=2. sum=2, below target 7.

  • l=0· arr[0] = 2
  • r=0· arr[0] = 2
Pseudocode
1FUNCTION minSubArrayLen(nums, target):
2 l = 0; sum = 0; minLen = infinity (no window found yet)
3 FOR each right edge r from 0 to the end of nums:
4 add nums[r] to sum
5 WHILE sum is at least target:
6 minLen = the smaller of minLen and the window size (r - l + 1)
7 subtract nums[l] from sum; move l one step right
8 RETURN minLen

← / → step · space play · Home restart

Every step in words

Show all 12 steps
  1. Grow the window by adding nums[0]=2. sum=2, below target 7.
  2. Add nums[1]=3. sum=5, still below target 7.
  3. Add nums[2]=1. sum=6, still below target 7.
  4. Add nums[3]=2. sum=8 >= target 7! Window [0,3] (length 4) qualifies — record minLen=4.
  5. Shrink from the left: subtract nums[0]=2, sum=6. Now below target, so stop shrinking — minLen stays 4.
  6. Add nums[4]=4. sum=10 >= target 7. Window [1,4] is length 4 — same as the current best.
  7. Shrink: subtract nums[1]=3, sum=7 — still >= target. Window [2,4] (length 3) beats the best — minLen=3.
  8. Shrink again: subtract nums[2]=1, sum=6 — now below target. Stop shrinking.
  9. Add nums[5]=3. sum=9 >= target 7. Window [3,5] is length 3 — matches the current best.
  10. Shrink: subtract nums[3]=2, sum=7 — still >= target. Window [4,5] (length 2) beats the best — minLen=2!
  11. Shrink again: subtract nums[4]=4, sum=3 — now below target. Stop shrinking.
  12. Array exhausted. The smallest window with sum >= 7 is [4,3] at indices 4-5, length 2. Answer: 2.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.