Minimum Size Subarray Sum - Problem

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.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,1,2,4,3], target = 7
Output: 2
💡 Note: The subarray [4,3] has sum 7 which is ≥ target, and length 2 is minimal. Other valid subarrays like [2,3,1,2] have length 4.
Example 2 — Single Element
$ Input: nums = [1,4,4], target = 4
Output: 1
💡 Note: Single element [4] already meets the target requirement with minimum length 1.
Example 3 — No Solution
$ Input: nums = [1,1,1,1,1,1,1,1], target = 11
Output: 0
💡 Note: Total sum is 8 < 11, so no subarray can achieve target sum ≥ 11.

Constraints

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

Visualization

Tap to expand
Minimum Size Subarray Sum INPUT Array: nums 2 i=0 3 i=1 1 i=2 2 i=3 4 i=4 3 i=5 target = 7 Find shortest subarray with sum >= 7 nums=[2,3,1,2,4,3], target=7 SLIDING WINDOW ALGORITHM 1 Initialize Pointers left=0, right=0, sum=0 2 Expand Window Add nums[right] to sum 3 Shrink if sum >= target Update minLen, move left 4 Continue until end Return minLen or 0 Window Example: 2 3 1 2 4 3 sum=7 Time: O(n) | Space: O(1) Two pointers, single pass FINAL RESULT Optimal subarray found: 2 3 1 2 4 3 Subarray [4, 3] at index 4-5 Sum: 4 + 3 = 7 >= target Output 2 OK - Minimal Length! No single element >= 7 Length 2 is minimum Key Insight: The sliding window technique maintains a dynamic window that expands by moving the right pointer and contracts by moving the left pointer. When sum >= target, we shrink to find minimum length. This achieves O(n) time as each element is visited at most twice (once by each pointer). TutorialsPoint - Minimum Size Subarray Sum | Sliding Window Approach
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
125.0K Views
High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen