leetcode-study

209. Minimum Size Subarray Sum

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        """
        Find the minimal length of a contiguous subarray of which the sum is at least target.
        
        Parameters:
            target (int): The target sum that the subarray needs to meet or exceed.
            nums (List[int]): A list of positive integers.
            
        Returns:
            int: The minimal length of a subarray with sum >= target. Returns 0 if no such subarray exists.
        """
        n = len(nums)
        min_len = float('inf')  # Initialize the minimum subarray length to infinity.
        current_sum = 0         # This variable will store the sum of the current sliding window.
        left = 0                # Left pointer for the sliding window.
        
        # Iterate over nums with the right pointer.
        for right, value in enumerate(nums):
            current_sum += value  # Expand the window by adding the current element.
            # Once the current sum reaches or exceeds the target, try to shrink the window.
            while current_sum >= target:
                # Update the minimal length if the current window is smaller.
                min_len = min(min_len, right - left + 1)
                # Shrink the window from the left side.
                current_sum -= nums[left]
                left += 1
        
        # If min_len was never updated, return 0 (no valid subarray found).
        return 0 if min_len == float('inf') else min_len

Summary of Techniques and Approaches:

These approaches are broadly applicable across numerous DSA problems, aiding in optimizing both time and space complexities.