Sliding Window · Medium

Smallest Subarray with Sum at Least Target

Solve it on DeVert Campus - free code runner

Problem

You are given an array of n positive integers and an integer target. Find the length of the shortest contiguous subarray whose sum is greater than or equal to target. If no such subarray exists, report 0.

Input and output

Input: The first line contains two space-separated integers n and target. The second line contains n space-separated positive integers representing the array. Output: Print a single integer: the length of the shortest subarray with sum >= target, or 0 if no such subarray exists.

Example

Input:
6 7
2 3 1 2 4 3
Output:
2

Constraints

1 <= n <= 10^5 1 <= arr[i] <= 10^4 1 <= target <= 10^9

Key observation

This is the sliding-window twin of the Queue-category's 'Shortest Subarray With Sum At Least K' problem - THAT version explicitly allows negative numbers (needing a deque-based approach), while THIS version's all-positive guarantee is exactly what enables the simpler two-pointer technique.

Intuition

Find the shortest contiguous subarray of positive numbers whose sum reaches at least a target value. Brute force: Check every possible contiguous subarray directly, summing each and tracking the shortest one meeting the target - this costs O(n²), too slow for large arrays. Optimised: Because every value is POSITIVE, growing the window always increases the sum and shrinking it always decreases the sum - this monotonic behavior is exactly what makes the two-pointer sliding window valid, since both pointers only ever need to move FORWARD across the whole scan, giving true O(n) total work.

Step by step

1. Expand the RIGHT end of the window, adding to a running sum. 2. Whenever the running sum reaches AT LEAST the target, try shrinking from the LEFT as much as possible while still meeting the target, recording the window length each time. 3. Because all elements are POSITIVE, each element enters and leaves the window at most once, giving O(n) total work.

Complexity

Time: O(n) - both pointers move forward monotonically, so total combined movement is linear. Space: O(1) - just a running sum and window boundary trackers.

Edge cases

Handle the case where no subarray reaches the target (print 0), and the case where the entire array is required to reach the target. Since all elements are positive, growing the window always increases the sum.

Interview tip

Be explicit that this technique ONLY works because every value is guaranteed POSITIVE - if negative values were allowed, growing or shrinking the window wouldn't reliably increase or decrease the sum, and a different technique (prefix sums with a monotonic deque) would be needed instead.

All DSA problems