2Brute2Best
🔥0

Minimum Size Subarray Sum

Medium·LeetCode #209Basic Anchor
LeetCode
30-Second Mental ModelVariable Sliding Window (shortest valid)
Complexity:O(N²)→O(N)
Key Insight

Keep a window [left … right] and its sum. Move right forward one step at a time. Whenever the sum reaches target, the window is valid: record its length, then drop nums[left] to see if a shorter window still works. Keep shrinking while it stays valid.

Core Validity Invariant

The window is valid when sum ≥ target. Here, valid means "good enough to be an answer" — so we record it and then try to make it shorter.

01

Problem

You are given an array of positive integers nums and a positive number target.

Find the shortest contiguous subarray whose sum is at least target, and return its length. If no subarray reaches target, return 0.

Input

An integer target and an integer array nums.

Output

The length of the shortest subarray with sum ≥ target, or 0 if there is none.

Example 1
Input: target = 7, nums = [2, 3, 1, 2, 4, 3]
Output: 2

[4, 3] adds up to 7 and has length 2. No single element is 7 or more, so 2 is the shortest.

Example 2
Input: target = 4, nums = [1, 4, 4]
Output: 1

The single element [4] already reaches 4.

Example 3
Input: target = 11, nums = [1, 1, 1, 1, 1, 1, 1, 1]
Output: 0

The whole array only adds up to 8, so nothing reaches 11.

Constraints
  • • 1 ≤ target ≤ 10^9
  • • 1 ≤ nums.length ≤ 10^5
  • • 1 ≤ nums[i] ≤ 10^4 (every number is positive)
  • • Follow-up: an O(N) solution exists; also try an O(N log N) one.
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.

  1. 1.

    Is the answer a contiguous block or any set of elements?

  2. 2.

    Is the size of the block given, or is the size what I'm looking for?

  3. 3.

    If a block already has sum ≥ target, what happens to its sum if I make it longer? Do I care about longer blocks?

  4. 4.

    If a block's sum is too small, can removing an element ever fix it?

  5. 5.

    All numbers are positive. What does that guarantee about the sum when I add or remove an element?

03

Brute force approach

04

Better approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceFor each start, grow right until the sum reaches targetO(N²)O(1)
BetterRunning totals are sorted, so binary search the end for each startO(N log N)O(N)
OptimalGrow right; while sum ≥ target, record the length and shrink from the leftO(N)O(1)
09

Why does this belong to this pattern?

Clues in the problem statement
  • “contiguous subarray”The answer is a range [left … right] → think window.
  • “minimal length”The window size is the answer, not an input → variable window. Shortest → record inside the shrink loop.
  • “sum ≥ target”A sum can be updated in O(1) when one element enters or leaves.
  • “positive integers”Adding only raises the sum, removing only lowers it. This is what makes shrinking from the left safe.
Contiguous range+minimum length+sum ≥ target+all numbers positive→Variable Sliding Window (shortest valid)

This is the anchor for variable windows. The rule is simple (sum ≥ target), so you can focus on the shape: grow right every step, shrink left while you can. It is the shortest version: you shrink while the window is valid and record the answer inside the loop. Most other questions in this group ask for the longest window, where you shrink while it is invalid and record after the loop.

10

Don't make this mistake

Recording the answer outside the while loop
✗ while (sum >= target) { sum -= nums[left]; left++; } best = min(best, right - left + 1);
✓ while (sum >= target) { best = min(best, right - left + 1); sum -= nums[left]; left++; }

After the loop ends, the window is invalid (sum < target). Recording it would give a length that is too short and doesn't reach target. For shortest windows, record while the window is still valid.

Using `if` instead of `while` to shrink
✗ if (sum >= target) { ... left++; }
✓ while (sum >= target) { ... left++; }

After adding one big number, you may be able to drop several small ones from the left. An if drops only one and misses shorter answers.

Returning INT_MAX when there is no answer
✗ return best;
✓ return best == INT_MAX ? 0 : best;

The problem says to return 0 when no subarray reaches target.

Using this window when numbers can be negative

If negatives are allowed, removing an element from the left could increase the sum, so stopping the shrink early might skip a valid shorter window. The window only works because every number is positive. With negatives, you need prefix sums with a monotonic deque (LeetCode 862).

11

Want to implement this?

Write it yourself on LeetCode, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.