HomeLeetcode209. Minimum Size Subarray Sum - Leetcode Solutions

209. Minimum Size Subarray Sum – Leetcode Solutions

Description

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 totarget. If there is no such subarray, return 0 instead.

Examples:

Example 1:

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:

Input: target = 4, nums = [1,4,4]
Output: 1

Example 3:

Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0

Solution in Python

Python
from typing import List

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        # Initialize the left pointer of the window, the sum of the current window, and the result length.
        left = 0
        current_sum = 0
        min_length = float('inf')  # Start with an infinite length for comparison
        
        # Iterate over the array with the right pointer.
        for right in range(len(nums)):
            # Add the current element to the current sum.
            current_sum += nums[right]
            
            # While the current window sum is greater than or equal to the target,
            # try to minimize the window by moving the left pointer to the right.
            while current_sum >= target:
                # Update the minimum length with the size of the current window.
                min_length = min(min_length, right - left + 1)
                # Subtract the element at the left pointer from the current sum and move the left pointer to the right.
                current_sum -= nums[left]
                left += 1
        
        # If the minimum length is still infinity, it means no valid subarray was found, return 0.
        return min_length if min_length != float('inf') else 0

Detailed Explanation:

  1. Initialization:
    • left: The left pointer of the sliding window, initially set to 0.
    • current_sum: Tracks the sum of the current sliding window.
    • min_length: Tracks the minimal length of the subarray found, initialized to infinity to ensure any found subarray will update it.
  2. Iterating Over the Array:
    • The right pointer iterates over the array from left to right.
    • For each position of right, the corresponding nums[right] value is added to current_sum.
  3. Shrinking the Window:
    • While the sum of the current window (current_sum) is greater than or equal to the target:
      • Calculate the current window length (right - left + 1) and update min_length if this is the smallest found so far.
      • Move the left pointer one step to the right (shrinking the window from the left) and adjust current_sum accordingly.
  4. Returning the Result:
    • After the loop, if min_length is still set to infinity, no subarray was found that meets the criteria, so return 0.
    • Otherwise, return min_length, which represents the minimal length of the valid subarray.

This approach efficiently finds the smallest subarray with a sum greater than or equal to the target in O(n) time complexity.

Solution in Javascript

JavaScript
/**
 * @param {number} target
 * @param {number[]} nums
 * @return {number}
 */
var minSubArrayLen = function(target, nums) {
    // Initialize the left pointer of the sliding window, the current sum of the window, and the minimal length.
    let left = 0;
    let currentSum = 0;
    let minLength = Infinity;  // Start with an infinitely large length for comparison

    // Iterate over the array with the right pointer.
    for (let right = 0; right < nums.length; right++) {
        // Add the current element at the right pointer to the current sum.
        currentSum += nums[right];

        // While the current window's sum is greater than or equal to the target,
        // try to minimize the window size by moving the left pointer to the right.
        while (currentSum >= target) {
            // Update the minimal length with the size of the current window.
            minLength = Math.min(minLength, right - left + 1);
            // Subtract the element at the left pointer from the current sum and move the left pointer to the right.
            currentSum -= nums[left];
            left++;
        }
    }

    // If the minimal length is still Infinity, it means no valid subarray was found, so return 0.
    // Otherwise, return the minimal length.
    return minLength === Infinity ? 0 : minLength;
};

Solution in Java

Java
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        // Initialize the left pointer of the sliding window, the current sum of the window, and the minimum length.
        int left = 0;
        int currentSum = 0;
        int minLength = Integer.MAX_VALUE; // Start with a very large value for comparison

        // Iterate over the array with the right pointer.
        for (int right = 0; right < nums.length; right++) {
            // Add the current element at the right pointer to the current sum.
            currentSum += nums[right];

            // While the current window's sum is greater than or equal to the target,
            // try to minimize the window size by moving the left pointer to the right.
            while (currentSum >= target) {
                // Update the minimal length with the size of the current window.
                minLength = Math.min(minLength, right - left + 1);
                // Subtract the element at the left pointer from the current sum and move the left pointer to the right.
                currentSum -= nums[left];
                left++;
            }
        }

        // If the minimal length is still the maximum integer value, it means no valid subarray was found, so return 0.
        // Otherwise, return the minimal length.
        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }
}

Solution in C#

C#
public class Solution {
    public int MinSubArrayLen(int target, int[] nums) {
        // Initialize the left pointer of the sliding window, the current sum of the window, and the minimum length.
        int left = 0;
        int currentSum = 0;
        int minLength = int.MaxValue; // Start with a very large value for comparison

        // Iterate over the array with the right pointer.
        for (int right = 0; right < nums.Length; right++) {
            // Add the current element at the right pointer to the current sum.
            currentSum += nums[right];

            // While the current window's sum is greater than or equal to the target,
            // try to minimize the window size by moving the left pointer to the right.
            while (currentSum >= target) {
                // Update the minimal length with the size of the current window.
                minLength = Math.Min(minLength, right - left + 1);
                // Subtract the element at the left pointer from the current sum and move the left pointer to the right.
                currentSum -= nums[left];
                left++;
            }
        }

        // If the minimal length is still int.MaxValue, it means no valid subarray was found, so return 0.
        // Otherwise, return the minimal length.
        return minLength == int.MaxValue ? 0 : minLength;
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular