Minimum Size Subarray Sum

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array of **positive** integers nums and a positive integer target. Find the length of the shortest contiguous subarray whose elements add up to **at least** target. Return that minimum length. If no subarray (including the whole array) reaches target, return 0. Aim for an O(n) solution; an O(n log n) approach is a good follow-up discussion.

Examples

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
The subarray [4,3] sums to 7, and no single element reaches 7.
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
The whole array only sums to 8.
Input: target = 4, nums = [1,4,4]
Output: 1
The single element 4 already meets the target.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^4
  • 1 <= target <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems