Taro Logo

Minimum Size Subarray Sum

#1 Most AskedMedium
1 view
Topics:
ArraysTwo PointersSliding Windows

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

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
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are all numbers in the input array strictly positive integers, or could we encounter zeros or negative numbers?
  2. What should be returned if no contiguous subarray has a sum greater than or equal to the target?
  3. Can the length of the array exceed standard integer limits, or can I assume it fits comfortably in memory?
  4. If the target itself is greater than the sum of the entire array, is that considered a scenario where no valid subarray exists?
  5. Should I be concerned about integer overflow when calculating the running sum of the subarray elements?

Brute Force Solution

Approach

Imagine you have a long row of numbers and you need to find the shortest group of numbers next to each other that add up to at least a certain target value. The brute force strategy is like being extremely thorough and stubborn, checking every single possible starting point and every possible ending point to find all valid groups.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first number in the row.
  2. Consider every possible group of numbers that begins with this first number, starting with just that single number, then the first two numbers together, then the first three numbers, and so on until the end of the row.
  3. For every single one of these groups, add up the numbers inside to see if the total reaches or exceeds your target value.
  4. If a group reaches the target, measure how many numbers are in that group and remember this count.
  5. Next, move your starting point to the second number in the row and repeat the entire process, checking every possible group that begins there.
  6. Continue this exhaustive process by shifting your starting point one step to the right each time, testing every possible ending point until you have examined every conceivable group of adjacent numbers.
  7. Finally, look back at all the successful groups you found and pick the one with the smallest number of items, which is your answer.

Code Implementation

def min_sub_array_len(target_sum, numbers_list):
    shortest_length = float('inf')
    total_elements = len(numbers_list)

    # Iterate through every possible starting position to exhaustively check all potential subarrays
    for start_index in range(total_elements):
        current_sum = 0

        # Expand the subarray one element to the right to evaluate progressively larger groups
        for end_index in range(start_index, total_elements):
            current_sum += numbers_list[end_index]

            # Track the minimum length whenever the running sum successfully reaches the target threshold
            if current_sum >= target_sum:
                current_length = (end_index - start_index) + 1
                if current_length < shortest_length:
                    shortest_length = current_length
                break

    # Return zero if no valid subarray was found that meets or exceeds the target sum requirement
    if shortest_length == float('inf'):
        return 0

    return shortest_length

Big(O) Analysis

Time Complexity
O(n²) – For each of the n numbers in the array, the algorithm uses a nested loop to test every possible ending point extending to the right. The outer loop shifts the starting point n times, while the inner loop iterates through the remaining elements to sum them up. This forms a triangular pattern of checks resulting in approximately n * (n + 1) / 2 total operations. When we drop the constants and lower-order terms, this simplifies to an overall time complexity of O(n²).
Space Complexity
O(1) – The brute force strategy described only utilizes a few primitive scalar variables, such as loop counters for starting and ending points, a running sum, and a variable to remember the minimum length found so far. No additional data structures whose size scales with the input are created or maintained during the process. Therefore, the auxiliary space remains constant regardless of the total number of elements N in the input array. This simplifies our space complexity to Big O of 1.

Optimal Solution

Approach

Instead of testing every single possible group of numbers, the optimal approach uses a flexible window that expands and shrinks dynamically. By sliding this window across the items, we can instantly find the shortest collection that meets our goal without doing extra work.

Here's how the algorithm would work step-by-step:

  1. Imagine you are looking at a row of numbers through a sliding window or a moving frame.
  2. Begin with a small frame at the very start of the row, covering just enough numbers to reach or exceed your target sum.
  3. Once your frame is large enough to meet the goal, record its current length as a potential answer.
  4. Now, try to make your frame smaller from the front edge while still keeping the sum high enough to meet the target, thereby finding a tighter group.
  5. If the sum drops below your target because the frame became too small, slide the back edge forward to bring in fresh numbers and grow the frame again.
  6. Repeat this process of expanding the back and shrinking the front as you move across the row, always keeping track of the shortest valid frame you manage to create.
  7. Once you reach the end of the row, the smallest frame size you recorded is your final answer.

Code Implementation

def minSubArrayLen(target_sum, array_of_numbers):
    current_window_sum = 0
    minimum_length = float('inf')
    window_start_index = 0

    # Expand the window to accumulate enough sum and satisfy the target.
    for window_end_index in range(len(array_of_numbers)):
        current_window_sum += array_of_numbers[window_end_index]

        # Shrink the window from the left to find the minimal valid length.
        while current_window_sum >= target_sum:
            current_window_length = window_end_index - window_start_index + 1

            if current_window_length < minimum_length:
                minimum_length = current_window_length

            current_window_sum -= array_of_numbers[window_start_index]
            window_start_index += 1

    # Return zero if no valid subarray was found during the traversal.
    if minimum_length == float('inf'):
        return 0

    return minimum_length

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the sliding window approach where the right pointer iterates through all n elements of the array exactly once, expanding the window. The left pointer also moves at most n times in total as it shrinks the window whenever the target sum is met or exceeded. Because both pointers traverse the array independently without nested repetitions, the total operations scale linearly rather than quadratically. Summing these visits yields approximately 2n operations in the worst case, which simplifies to O(n).
Space Complexity
O(1) – The algorithm relies solely on a few primitive scalar variables, such as pointers for the sliding window boundaries, a running sum, and a variable to track the minimum length. These variables require a fixed amount of extra memory regardless of the input size N. No dynamic data structures, recursive calls, or auxiliary arrays are created during execution. Consequently, the auxiliary space complexity remains constant at O(1).

Edge Cases

No subarray meets or exceeds the target sum
How to Handle:
Initialize the minimum length to infinity and return zero if it remains unchanged at the end.
A single element in the array is greater than or equal to the target
How to Handle:
The sliding window will immediately recognize this as a valid window of length one and update the minimum length accordingly.
The sum of all elements in the array is less than the target
How to Handle:
The outer loop will consume the entire array without the window sum ever reaching the target, resulting in a return value of zero.
Empty array or null input passed as nums
How to Handle:
Guard clauses at the start of the function check for null or empty inputs and immediately return zero.
Array contains extremely large numbers or the total sum causes integer overflow
How to Handle:
While constraints state positive integers, using standard 64-bit integer types prevents overflow during window sum accumulation.
All elements in the array are equal and smaller than the target
How to Handle:
The sliding window correctly expands until the accumulated sum meets the target, then contracts to find the minimal length.
Target is very small such as one
How to Handle:
The sliding window will find the first element that is greater than or equal to one and immediately return a length of one.
Maximum possible array size with large values
How to Handle:
The O(N) sliding window approach efficiently processes the array in a single pass without exceeding time limits.
0/8 completed