Minimum Size Subarray Sum

Medium Sliding WindowArray

Problem

Given a positive integer target and a positive integer array, return the minimum length of a contiguous subarray whose sum ≥ target. Return 0 if none exists.

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

Constraints

Approach — Sliding Window

This is a Sliding Window problem. The idea: keep a moving window over the sequence, expanding and shrinking it while tracking the answer in a single pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time.

Solution code

Python

class Solution:
    def minSubArrayLen(self, target, nums):
        left = total = 0
        best = len(nums) + 1
        for right, x in enumerate(nums):
            total += x
            while total >= target:
                best = min(best, right - left + 1)
                total -= nums[left]
                left += 1
        return best if best <= len(nums) else 0

Java

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

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Minimum Size Subarray Sum interactively → ← All solutions