LeetCode 2875: Minimum Size Subarray in Infinite Array

Problem Description

Explanation:

To solve this problem, we can use a sliding window approach. We will maintain two pointers start and end that represent the current window. We will keep expanding the window by incrementing the end pointer until the sum of elements within the window is less than or equal to the target. Once the sum exceeds the target, we will increment the start pointer to shrink the window while keeping track of the minimum window length found so far.

Algorithmic Idea:

  1. Initialize start and end pointers to 0.
  2. Iterate over the array using the end pointer, expanding the window and updating the sum.
  3. While the sum is greater than or equal to the target, update the minimum window length and increment the start pointer to shrink the window.
  4. Repeat steps 2 and 3 until the end of the array.
  5. Return the minimum window length if found, otherwise return -1.

Time Complexity:

The time complexity of this algorithm is O(n) where n is the number of elements in the input array.

Space Complexity:

The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.

Solutions

public int minSubArrayLen(int target, int[] nums) {
    int n = nums.length;
    int start = 0, end = 0, sum = 0, minLen = Integer.MAX_VALUE;
    
    for (; end < n; end++) {
        sum += nums[end];
        
        while (sum >= target) {
            minLen = Math.min(minLen, end - start + 1);
            sum -= nums[start];
            start++;
        }
    }
    
    return minLen == Integer.MAX_VALUE ? -1 : minLen;
}

Loading editor...