InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Minimum Size Subarray Sum

medium Original ↗ 00:00

Problem

Given an array nums of positive integers and a positive integer target, return the length of the shortest contiguous subarray whose sum is greater than or equal to target. If no subarray reaches target, return 0.

Two details matter: elements are strictly positive (this is what makes the fast solution work), and you want the minimum length — a reversal of the more common “longest valid window” setup.

Examples

  • target = 7, nums = [2, 3, 1, 2, 4, 3]2[4, 3] sums to 7; no single element reaches 7.
  • target = 4, nums = [1, 4, 4]1 — a single 4 already meets the target.
  • target = 11, nums = [1, 1, 1, 1, 1]0 — the whole array sums to 5, so no valid subarray exists.

Constraints

  • 1 <= target <= 10^9
  • 1 <= len(nums) <= 10^5
  • 1 <= nums[i] <= 10^4

O(n²) subarray enumeration is ~5 * 10^9 steps at n = 10^5. The expected solution is O(n); an O(n log n) prefix-sum + binary-search solution is a classic follow-up.

Think about it first

Hint 1 Because every element is positive, growing a window strictly increases its sum and shrinking strictly decreases it. Which direction do you move when the sum is too small? When it's big enough?
Hint 2 You want the shortest window meeting the target — so once the window's sum reaches target, greedily shrink it from the left while it still qualifies, recording each qualifying length.
Hint 3 One pass: extend right, adding to a running sum; then while sum >= target, record right - left + 1 and subtract nums[left], advancing left. Each pointer moves at most n times.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug