Minimum Size Subarray Sum

Photo by on Unsplash

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Example 1:

Example 2:

Example 3:


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


We could keep 2 pointers ,one for the start and another for the end of the current subarray, and make optimal moves so as to keep the sum greater than s as well as maintain the lowest size possible.


  • Initialize left pointer to 0 and sum to 0
  • Iterate over the nums:
  • Add nums[i] to sum.
  • While sum is greater than or equal to s:
  • Update result=min(result,i+1−left), where i+1−left is the size of current subarray.
  • It means that the first index can safely be incremented, since, the minimum subarray starting with this index with sum≥s has been achieved
  • Subtract nums[left] from sum and increment left.

Complexity analysis

  • Time complexity: O(n). Single iteration .
  • Space complexity: O(1) extra space.

If you like the content please follow me here @medium and at LinkedIn

Full Stack Programmer, love to solve problem’s during free time.