Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
A medium sliding window problem, graded against 7 test cases (4 of them hidden).
A moving window over a contiguous run, expanding and contracting to hold an invariant.
Reach for it when you see: "Longest/shortest contiguous subarray or substring satisfying X."
More Sliding Window problems →Because every element is positive, the window sum is monotonic in the window size, which makes a two-pointer window valid. Expand `right` and add to the running sum. Whenever the sum is at least `target`, record the window length and shrink from `left` - keep shrinking while the sum still meets the target, since a shorter qualifying window is always better.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.