Minimum Size Subarray Sum


Minimum Size Subarray Sum – LeetCode #209


Problem Statement

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

Return the minimum length of a contiguous subarray of which the sum is greater than or equal to target.
If there is no such subarray, return 0.


Examples


Constraints


Intuition

We want to find the smallest window (subarray) whose elements sum to at least target.

This problem naturally fits the Variable Size Sliding Window – Conditional Based pattern:


Approach

  1. Initialize two pointers l = 0, r = 0.

  2. Maintain a running sum and set minLen to Integer.MAX_VALUE.

  3. Loop through the array with r:

    • Add nums[r] to sum.

    • If sum ≥ target, try shrinking the window from the left while keeping the sum valid:

      • Update minLen with the current window length r - l + 1.

      • Subtract nums[l] and increment l.

  4. After the loop, return minLen if updated, otherwise return 0.


Java Code

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int l = 0;
        int sum = 0;
        int min = Integer.MAX_VALUE;

        for (int r = 0; r < nums.length; r++) {
            sum += nums[r];

            while (sum >= target) {
                min = Math.min(min, r - l + 1);
                sum -= nums[l];
                l++;
            }
        }

        return min == Integer.MAX_VALUE ? 0 : min;
    }
}

Time and Space Complexity


Dry Run

Input:

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

Steps:

Final min = 2


Conclusion

This problem demonstrates the power of the Variable Size Sliding Window – Condition Based pattern, especially when the task is to minimize or maximize a window size based on a condition (in this case, a sum threshold).

The key to solving it efficiently is:

This technique is highly reusable for: