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
- 1 ≤ nums.length ≤ 10⁵
- 1 ≤ nums[i] ≤ 10⁴ (all positive, so the window sum only grows when it widens)
- 1 ≤ target ≤ 10⁹
- Aim for O(n); O(n log n) is the follow-up
Edge cases to test
- No subarray reaches the target:
0 - One element alone reaches it
- The whole array is needed
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 bestC++
#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
- Best Time to Buy and Sell Stock (Easy)
- Maximum Sum Subarray of Size K (Easy)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)
- Subarrays with K Different Integers (Hard)