MediumArraysSliding WindowBinary Search

Minimum Size Subarray Sum

LeetCode
2 approaches, code in all languages

You are handed an array of positive integers together with a target value. Your job is to find the length of the shortest contiguous stretch of elements whose sum is at least as large as the target. When no stretch of the array can reach the target, report 0 instead.

Because every element is strictly positive, extending a window to the right can only increase its sum and dropping an element from the left can only decrease it. That monotonic behaviour is exactly what lets a single sweep find the shortest qualifying window.

Example 1

Input: target = 7, nums = [2,3,1,2,4,3]

Output: 2

The two elements 4 and 3 sit next to each other and add up to 7, and no shorter run of elements manages to reach 7.

Example 2

Input: target = 4, nums = [1,4,4]

Output: 1

A single card holding 4 already meets the target on its own, so the minimal length is 1.

Constraints

  • 1 ≤ target ≤ 10^9
  • 1 ≤ nums.length ≤ 10^5
  • 1 ≤ nums[i] ≤ 10^4
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now