#209

Minimum Size Subarray Sum

Medium
ArrayBinary SearchSliding WindowPrefix SumSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses the sliding window technique to efficiently find the minimum length of a subarray. This approach expands and contracts the window based on the current sum, ensuring we only traverse the array once.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers (left and right) and a variable to track the current sum.
  2. 2Step 2: Expand the right pointer to increase the current sum until it meets or exceeds the target.
  3. 3Step 3: Once the target is met, try to contract the left pointer to find the minimal length while still meeting the target.
  4. 4Step 4: Update the minimum length if a shorter valid subarray is found.
  5. 5Step 5: Repeat until the right pointer reaches the end of the array.
solution.py11 lines
1def minSubArrayLen(target, nums):
2    left = 0
3    current_sum = 0
4    min_length = float('inf')
5    for right in range(len(nums)):
6        current_sum += nums[right]
7        while current_sum >= target:
8            min_length = min(min_length, right - left + 1)
9            current_sum -= nums[left]
10            left += 1
11    return min_length if min_length != float('inf') else 0

Complexity note: The time complexity is O(n) because each element is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(1) since we only use a few variables.

  • 1Using a sliding window can significantly reduce time complexity.
  • 2Understanding when to expand and contract the window is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.