Minimum Size Subarray Sum

Updated on 18 June, 2025
Minimum Size Subarray Sum header image

Problem Statement

The challenge requires the identification and return of the minimal length of a contiguous subarray from the array of positive integers nums, where the sum of the elements in the subarray is at least equal to the given target. If no such subarray exists that meets or exceeds the target sum, the function should return 0.

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

Constraints

  • 1 <= target <= 109
  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104

Approach and Intuition

Let's break down the overall strategy to tackle the problem using the provided examples:

Understanding Through Examples

  1. Example 1:
    Input: target = 7, nums = [2,3,1,2,4,3]
    Output: 2
    Explanation: The smallest subarray that meets the target sum of 7 is [4, 3]. The length of this subarray is 2, which is the smallest possible length to achieve the sum.

  2. Example 2:
    Input: target = 4, nums = [1,4,4]
    Output: 1
    Explanation: Here, the subarray [4] directly meets the target, and since it is a single element, its length is the minimum possible length of 1.

  3. Example 3:
    Input: target = 11, nums = [1,1,1,1,1,1,1,1]
    Output: 0
    Explanation: In this case, the sum of all elements in the array is less than the target, thus no feasible subarray exists, and we return 0.

Strategy Development

  • Utilize a sliding window technique to dynamically adjust the size of the subarray:

    • Start with two pointers both at the beginning of the array.
    • Expand the window by moving the right pointer to increase the sum.
    • Once the sum exceeds or equals the target, attempt to shrink the window from the left to try and find a smaller subarray that still meets the conditions.
    • Continue adjusting the window until you have checked all potential subarrays.
  • Maintain a record of the minimum length found that meets the conditions.

Why this works: This method efficiently traverses the list without extra passes for each subarray configuration, using a dynamic sliding window to adjust subarray bounds based on current sum relative to target. This optimality ensures it meets the constraints of handling large input sizes within a reasonable time complexity.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int minimumSubArrayLength(int target, vector<int>& values) {
        int start = 0, end = 0, currentSum = 0;
        int minLength = INT_MAX;

        for(end = 0; end < values.size(); end++) {
            currentSum += values[end];

            while (currentSum >= target) {
                minLength = min(minLength, end - start + 1);
                currentSum -= values[start];
                start++;
            }
        }

        return minLength == INT_MAX ? 0 : minLength;
    }
};

This summary focuses on a C++ function designed to find the minimum length of a subarray from a given array values where the sum of the subarray is at least as large as a specified target value. The solution involves an efficient approach using a sliding window technique, optimizing for both space and time complexities.

  • You start by initializing two pointers, start and end, both set to 0. These pointers will define the current subarray.
  • currentSum is used to maintain the sum of the elements within the window defined by start and end.
  • minLength is initialized with INT_MAX to store the minimum length of the subarray found that meets the condition.

For the operation:

  1. Incrementally explore the array using the end pointer, adding the current element to currentSum.
  2. Once currentSum equals or surpasses the target sum, attempt to shrink the window from the left using the start pointer and updating minLength accordingly.

The loop controlled by the end pointer expands the subarray until the currentSum exceeds or meets the target, while the nested loop shrinks the subarray from the start to find the smallest possible length.

If no valid subarray is found (i.e., minLength remains INT_MAX), the function returns 0. Otherwise, the smallest length of the subarray satisfying the required sum condition is returned. This technique ensures that the solution is achieved with a linear time complexity relative to the input array size, making it efficient for large datasets.

java
class Solution {
    public int minimumSizeSubarray(int target, int[] array) {
        int startIndex = 0, endIndex = 0, sum = 0;
        int minLength = Integer.MAX_VALUE;

        for(endIndex = 0; endIndex < array.length; endIndex++) {
            sum += array[endIndex];

            while (sum >= target) {
                minLength = Math.min(minLength, endIndex - startIndex + 1);
                sum -= array[startIndex++];
            }
        }

        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }
}

The Java solution provided tackles the problem of finding the minimum length of a contiguous subarray for which the sum is equal to or greater than a given target.

Follow these steps to comprehend the working mechanism of the provided code:

  1. Initialize two pointers, startIndex and endIndex, for managing the sliding window's bounds, along with a sum variable to keep track of the current sum of the subarray.
  2. Start iterating over the array with the endIndex. During each iteration, add the current element (pointed by endIndex) to sum.
  3. Use a nested while loop to check if the current sum is greater than or equal to the target. If true:
    • Update minLength to be the smaller value between the current minLength and the size of the current window (endIndex - startIndex + 1).
    • Reduce the sum by the value of the element at startIndex and then increment startIndex to potentially reduce the window size.
  4. Continue expanding the window size by moving the endIndex until the end of the array is reached.
  5. End the iteration and check if minLength was updated from its initialized value. If it remains as Integer.MAX_VALUE, return 0 (indicating no such subarray was found), otherwise return the value of minLength.

This code efficiently finds the smallest window in the array that satisfies the condition using a sliding window technique. The algorithmic complexity is optimized to be linear, O(n), due to the single traversal of the array with growing and shrinking window adjustments.

python
class Solution:
    def smallestSubarrayWithSum(self, threshold: int, numbers: List[int]) -> int:
        start_index = 0
        minimum_length = float('inf')
        current_sum = 0

        for end_index in range(len(numbers)):
            current_sum += numbers[end_index]

            while current_sum >= threshold:
                minimum_length = min(minimum_length, end_index - start_index + 1)
                current_sum -= numbers[start_index]
                start_index += 1

        return minimum_length if minimum_length != float('inf') else 0

The provided Python code defines a method for finding the minimum length of a contiguous subarray where the sum of the subarray's elements is at least as large as a given threshold. The method is a part of the Solution class and is named smallestSubarrayWithSum. It takes two parameters: the threshold integer, threshold, and a list of integers, numbers.

Here's a step-by-step breakdown of how the method works:

  1. Initialize start_index to 0 to keep track of the beginning of the current subarray.
  2. Set minimum_length to infinity (float('inf')) to store the smallest length found that meets the condition.
  3. Set current_sum to 0 to hold the sum of elements in the current sliding window.

The code then iterates through each element in the numbers list:

  1. For each element pointed at by end_index, add this element to current_sum.
  2. Check if current_sum is greater than or equal to threshold.
  3. If it is, continuously adjust the window by subtracting the element at start_index from current_sum and incrementing start_index, to find the smallest possible length of a qualifying subarray that starts from the current start_index.
  4. Update minimum_length if the current subarray's length (determined by end_index - start_index + 1) is less than the previously found minimum_length.
  5. Continue this process until the entire list is traversed.

Finally, the method returns:

  • The value of minimum_length if it's not infinity, which represents the length of the smallest subarray that meets the requirement.
  • 0 if no such subarray exists (i.e., if minimum_length remains set to infinity).

This algorithm effectively utilizes a sliding window technique to efficiently find the required subarray without checking all possible subarrays explicitly, thus optimizing performance.

Comments

No comments yet.