Minimum Size Subarray Sum

MediumSliding Window · Prefix Sum🧩 Sliding WindowLeetCode #209 ↗Updated

Problem

You get an array nums of positive integers and a positive target. Find the length of the shortest contiguous subarray whose sum is at least target. If no subarray reaches the target, return 0.
Inputtarget = 7, nums = [2,3,1,2,4,3]Output2 (subarray [4,3])
Inputtarget = 4, nums = [1,4,4]Output1
Inputtarget = 11, nums = [1,1,1,1,1]Output0

1 ≤ n ≤ 105  ·  1 ≤ nums[i] ≤ 104  ·  1 ≤ target ≤ 109  ·  Follow-up: after O(n), try an O(n log n) solution.

Try it yourself

Java
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
All values are positive, so growing a window only raises its sum and shrinking only lowers it. That monotonicity lets two pointers sweep once: extend the right edge until the sum is big enough, then squeeze the left edge as far as possible.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceEvery Start, Running Sum

Time O(n2)Space O(1)

Fix each start index and extend the end one step at a time while keeping a running sum. The first end where the sum reaches target gives the shortest window for that start, so we can stop extending immediately.

Java
public int minSubArrayLen(int target, int[] nums) {
    int n = nums.length;
    int best = Integer.MAX_VALUE;
    for (int start = 0; start < n; start++) {
        int sum = 0;
        for (int end = start; end < n; end++) {
            sum += nums[end];
            if (sum >= target) {
                best = Math.min(best, end - start + 1);
                break; // longer windows from this start can't be shorter
            }
        }
    }
    return best == Integer.MAX_VALUE ? 0 : best;
}

Correct and simple, but quadratic — too slow for n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceEvery Start, Running SumO(n2)O(1)
BetterPrefix Sums + Binary SearchO(n log n)O(n)
OptimalVariable-Size Sliding WindowO(n)O(1)
Common pitfalls
  • Using if instead of while to shrink — misses shorter windows.
  • Returning Integer.MAX_VALUE when nothing qualifies instead of 0.
  • Applying the window to arrays with negatives — the monotonic argument no longer holds.
Interview tips
  • Point out the positivity constraint early; it is what makes two pointers valid.
  • Argue O(n) by counting moves: each pointer advances at most n times.
  • Offer the prefix-sum + binary-search version when asked for O(n log n).
Pattern
Variable sliding window → shortest/longest contiguous range with a monotone condition over non-negative values.
My notes saved in this browser