Skip to content

Sliding Window — Minimum Size Subarray Sum ​

↗ LeetCode: Minimum Size Subarray Sum · Medium · pattern chapter →

Asked atAmazonGoogleMicrosoftMeta

Given a positive-int array nums and target target, return the minimal length of a contiguous subarray whose sum is at least target. Return 0 if none.

Example 1 — target = 7, nums = [2,3,1,2,4,3] → 2 (the subarray [4,3] sums to 7) Example 2 — target = 4, nums = [1,4,4] → 1 (single 4) Example 3 — target = 11, nums = [1,1,1,1,1,1,1,1] → 0 (impossible)

Constraints — 1 ≤ n ≤ 10⁵; 1 ≤ nums[i], target ≤ 10⁴. All values positive.. Brute enumerates all subarrays in O(n²) = 10¹⁰ ops (TLE past n=10⁴). Sliding window is O(n) = 10⁵ ops = <5 ms.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — All subarrays ​

Intuition. For each i, expand j and accumulate the sum. On first sum ≥ target, record length and break the inner loop (extending further only lengthens).

java
int minSubArrayLenBrute(int target, int[] nums) {
    int best = Integer.MAX_VALUE;
    for (int i = 0; i < nums.length; i++) {
        int sum = 0;
        for (int j = i; j < nums.length; j++) {
            sum += nums[j];
            if (sum >= target) { best = Math.min(best, j - i + 1); break; }
        }
    }
    return best == Integer.MAX_VALUE ? 0 : best;
}
Execution Trace
Brute — target=7, nums=[2,3,1,2,4,3]
ij203112234435sum = 8len = 4best = 4
Step 1 / 42+3+1+2 ≥ 7 → best=4

Complexity — Time O(n²) worst; Space O(1).


Approach 2 — Sliding window (positives only) ​

Insight from brute. With positive values, growing right monotonically increases sum, and shrinking left monotonically decreases it. So we can extend right until sum ≥ target, then shrink left while the window is still valid — tracking the min length.

java
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;
}
Execution Trace
Sliding — target=7, nums=[2,3,1,2,4,3]
leftright203112234435sum = 8best = 4
Step 1 / 4sum ≥ 7 — record len 4; shrink

Complexity — Time O(n) — each index enters and leaves the window at most once; Space O(1).


Approach 3 — Prefix sum + binary search (extends to negatives? No) ​

Insight from sliding. Sliding window fails once values can be negative — shrinking doesn't monotonically decrease sum. A prefix-sum + binary-search approach handles positives at O(n log n) and generalizes to a monotonic deque approach for negatives (see Shortest Subarray with Sum at Least K).

java
int minSubArrayLenBS(int target, int[] nums) {
    int n = nums.length;
    int[] pref = new int[n + 1];
    for (int i = 0; i < n; i++) pref[i + 1] = pref[i] + nums[i];
    int best = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
        int need = pref[i] + target;
        int j = Arrays.binarySearch(pref, i + 1, n + 1, need);
        if (j < 0) j = -j - 1;
        if (j <= n) best = Math.min(best, j - i);
    }
    return best == Integer.MAX_VALUE ? 0 : best;
}

Complexity — Time O(n log n); Space O(n). Loses to sliding for positives-only but sets up the generalization.


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceInterview grade
All subarraysO(n²)O(1)baseline
Sliding windowO(n)O(1)expected optimum for positives
Prefix + binary searchO(n log n)O(n)polish — generalizes to negatives via deque

When to use which ​

  • First pass — sliding window is the right answer for positives.
  • "What if values can be negative?" → mention the generalization: monotonic deque on prefix sums.
  • "Return the subarray itself" → track (bestL, bestLen) and slice.
  • "Sum exactly equal to target" → different problem — needs prefix-sum + hash-map (see Subarray Sum Equals K).
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help