209. Minimum Size Subarray Sum ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Array
, Two Pointers
, Sliding Window
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a subarray whose sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
๐น Example 1:
Input:
Output:
Explanation: The subarray [4,3]
has the minimal length under the problem constraint.
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
Explanation: No subarray sums up to or exceeds 11.
1 <= target <= 10^9
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^4
To solve this problem, we can use the Sliding Window approach:
Initialize Pointers: Use two pointers left
and right
to represent the current window, and initialize sum
to keep track of the current sum of the window.
Expand and Shrink the Window:
Expand the right
pointer to include elements in the window.
When the sum
of the window is greater than or equal to target
, try to shrink the window from the left by moving the left
pointer to minimize the subarray length.
Update the Result:
Keep track of the minimal length of such subarrays.
Return the minimal length found, or 0
if no valid subarray is found.
O(n): Each element is added to the sum and removed from the sum at most once.
O(1): No additional space is used except for the variables to store the current sum, pointers, and the result.
You can find the full solution .