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 Problem OverviewInput Array:231243Target: 7Find Minimum Subarray:43Sum = 4 + 3 = 7 ≥ 7 ✓Length = 2Other valid subarrays:[2,3,1,2] = 8 ≥ 7 (length 4)[3,1,2,4] = 10 ≥ 7 (length 4)Output: 2 (minimum length)
Understanding the Visualization
1
Input
Array of positive integers and target sum
2
Process
Find shortest contiguous subarray with sum ≥ target
3
Output
Length of minimum subarray (0 if impossible)
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find the shortest subarray by expanding when sum is too small and contracting when sum meets target
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