LeetCode 209: Minimum Size Subarray Sum Solution
Master LeetCode problem 209 (Minimum Size Subarray Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
209. Minimum Size Subarray Sum
Problem Explanation
Explanation
To solve this problem, we can use a two-pointer sliding window approach. We initialize two pointers, left and right, pointing to the start of the array. We keep expanding the window by moving the right pointer until the sum of the subarray between left and right is less than the target. Once the sum is greater than or equal to the target, we update the minimum length found so far and move the left pointer to shrink the window while keeping the sum greater than or equal to the target. We continue this process until we reach the end of the array.
Time Complexity
The time complexity of this approach is O(n), where n is the number of elements in the input array.
Space Complexity
The space complexity of this approach is O(1) as we are using constant extra space.
Solution Code
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int left = 0, right = 0;
int sum = 0;
int minLength = Integer.MAX_VALUE;
while (right < n) {
sum += nums[right];
while (sum >= target) {
minLength = Math.min(minLength, right - left + 1);
sum -= nums[left];
left++;
}
right++;
}
return minLength == Integer.MAX_VALUE ? 0 : minLength;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 209 (Minimum Size Subarray Sum)?
This page provides optimized solutions for LeetCode problem 209 (Minimum Size Subarray Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 209 (Minimum Size Subarray Sum)?
The time complexity for LeetCode 209 (Minimum Size Subarray Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 209 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 209 in Java, C++, or Python.