Medium · Variable Sliding Window
Understand → Visualise → Practice.
Given positive integers, return the shortest contiguous subarray with sum at least `target`, or 0 if none exists.
With only positive numbers, extending the window increases its sum and shrinking decreases it. After each extension, shrink from the left while the sum is still at least the target.
Add nums[right] to the running sum.
While sum ≥ target, record the length, subtract nums[left] and move left.
Return the shortest length found, or 0 if none.
O(n) time and O(1) space.
This shrinking rule is invalid when negative numbers are allowed.
Read the full guide first: Two Pointers and Sliding Windows.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.