The challenge
Return the minimum length of a contiguous subarray with sum at least target. Return 0 when no such subarray exists.
Positive integers only; target > 0. Empty input returns 0.
Example
[2, 3, 1, 2, 4, 3], target = 7 → 2, from [4, 3].
Use the walkthrough below to inspect the input and each state change.
See Minimum length sum, step by step
Expand, shrink, and inspect the window state.
6 elements · zero-based indicestarget = 7
Current windowRecorded answerOutside window
- Left
- 0
- Right
- -1
- Length
- 0
Step 01 / 18
Start with an empty window
Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.
left = 0; right = −1Answer so far
0
View exact input
Input: [2,3,1,2,4,3] · target = 7
Current window is empty.
Put it into code
Positive values make expansion increase the sum and shrinking decrease it. Record a valid window before removing its left element.
Indices are zero-based. C++ uses C++17 or later.
def min_subarray_length(nums, target):
# Positive integers; target > 0.
left = total = 0
best = len(nums) + 1
for right, value in enumerate(nums):
total += value
while total >= target:
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == len(nums) + 1 else best#include <algorithm>
#include <array>
#include <deque>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int min_subarray_length(const vector<int>& nums, long long target) {
int left = 0, best = (int)nums.size() + 1;
long long total = 0;
for (int r = 0; r < (int)nums.size(); ++r) {
total += nums[r];
while (total >= target) {
best = min(best, r - left + 1);
total -= nums[left++];
}
}
return best == (int)nums.size() + 1 ? 0 : best;
}