Command Palette

Search for a command to run...

Problem 7.3 · Sliding WindowMedium

Minimum Size Subarray Sum

What it teaches: The "shortest" variant: shrink while the window is valid, recording its length each time.

Practise it on judges as “Minimum Size Subarray Sum”.

The problem

Given an array of positive integers nums and a positive target, return the minimal length of a contiguous subarray whose sum is at least target, or 0 if there's none.

Example 1

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

[4, 3].

Example 2

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

Example 3

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

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴
  • 1 ≤ target ≤ 10⁹

Pattern clues in the wording

  • → "Minimal length" contiguous subarray with a sum condition
  • → All positive → shrinking always lowers the sum

These clues point to Sliding Window: Variable Size: Grow the window with the right pointer; when it breaks a rule, shrink it from the left until it's valid again.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        return 0;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
target = 7
nums = [2,3,1,2,4,3]
2
2
target = 4
nums = [1,4,4]
1
3
target = 11
nums = [1,1,1,1,1,1,1,1]
0

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: shrink while valid

Time O(n) Space O(1)

Add nums[right]. While the sum is at least target, record the length and remove nums[left].

▶ Dry run: Grow, then squeezetarget = 7, nums = [2, 3, 1, 2, 4, 3]
2
0
↑L
3
1
1
2
2
3
↑R
4
4
3
5

State(vars)

sum = 8best = 4

Step 1/4Grow to [2, 3, 1, 2]: sum 8 ≥ 7. Record 4, then remove 2: sum 6 < 7.

Approach 1
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0, sum = 0, best = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {
                best = Math.min(best, right - left + 1);
                sum -= nums[left++];
            }
        }
        return best == Integer.MAX_VALUE ? 0 : best;
    }
}

Verdict: Each element enters and leaves once.

Before you submit

Edge cases and common mistakes

Test these inputs

  • No valid subarray → 0
  • A single element ≥ target → 1
  • The whole array needed

Mistakes people make

  • Returning Integer.MAX_VALUE when nothing is found.
  • Recording the length after the shrink loop.

Interview

Follow-up questions

Can you do it in O(n log n) another way?