Algo-Sim › Sliding Window

Minimum Size Subarray Sum

Medium · Sliding Window · step through it in Java, Python and C++ on your own input

Find the length of the shortest contiguous subarray whose sum is at least target (0 if none).

Problem

Given an array of positive integers nums and a positive integer target, return the length of the shortest contiguous subarray whose sum is at least target. If no subarray reaches target, return 0.

Constraints

Edge cases to test

Follow-up questions

Why does the window need positive numbers?
With positives only, shrinking always lowers the sum, so the window can move left-to-right once: O(n). Negatives break that; use prefix sums with a monotonic deque instead (LC 862).
Can you do it in O(n log n) another way?
Prefix sums are increasing, so for each i binary search the first j with prefix[j] ≥ prefix[i] + target.

Solution

Java

public int minSubArrayLen(int target, int[] nums) {
    int left = 0, sum = 0;
    int 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];
            left++;
        }
    }
    return best == Integer.MAX_VALUE ? 0 : best;
}

Python

def min_sub_array_len(target, nums):
    left, window_sum = 0, 0
    best = float("inf")
    for right in range(len(nums)):
        window_sum += nums[right]
        while window_sum >= target:
            best = min(best, right - left + 1)
            window_sum -= nums[left]
            left += 1
    return 0 if best == float("inf") else best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minSubArrayLen(int target, vector<int> &nums) {
        int left = 0, sum = 0;
        int best = INT_MAX;
        for (int right = 0; right < int(nums.size()); right++) {
            sum += nums[right];
            while (sum >= target) {
                best = std::min(best, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
        return best == INT_MAX ? 0 : best;
    }
};

More Sliding Window problems