209. Minimum Size Subarray Sum ๐
Difficulty: Medium
- Tags: Array
, Two Pointers
, Sliding Window
Problem Statement ๐
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.
Examples ๐
๐น 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.
Constraints โ๏ธ
1 <= target <= 10^9
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^4
Solution ๐ก
To solve this problem, we can use the Sliding Window approach:
Initialize Pointers: Use two pointers
left
andright
to represent the current window, and initializesum
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 totarget
, try to shrink the window from the left by moving theleft
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.
Java Solution
Time Complexity โณ
O(n): Each element is added to the sum and removed from the sum at most once.
Space Complexity ๐พ
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 here.
Last updated