Skip to content
MediumSliding WindowAI interview only

Minimum Size Subarray Sum

Asked atmetagoogleamazonmicrosoftbloomberggoldman-sachs

01 · 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 non-empty sequence of elements within an array.

02 · Examples

Example 01
Input
target = 7, nums = [2,3,1,2,4,3]
Output
2

The subarray [4,3] has sum 7 which is >= target, and its length 2 is the smallest possible.

Example 02
Input
target = 4, nums = [1,4,4]
Output
1

The single element [4] already meets the target of 4.

Example 03
Input
target = 11, nums = [1,1,1,1,1,1,1,1]
Output
0

The total sum of the array is 8 which is less than 11, so no valid subarray exists.

03 · Constraints

  • 011 <= target <= 109
  • 021 <= nums.length <= 105
  • 031 <= nums[i] <= 104

04 · Optimal complexity

Time
O(n)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.