oneby7

Sliding Window Longest or shortest window

175. Minimum Size Subarray Sum

Medium

You are given an array of positive integers nums and a positive integer target. Return the length of the shortest subarray whose elements add up to at least target. If no subarray adds up to that much, return 0.

A subarray is a contiguous, non-empty sequence of elements from nums.

Example 1

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

Output: 3

Explanation: No two neighbours reach 9: the largest pair, 3 + 5, makes 8. Three elements are enough, since [1, 3, 5] adds up to 9 and [3, 5, 2] adds up to 10.

Example 2

Input: nums = [2, 3, 1, 2], target = 10

Output: 0

Explanation: The whole array adds up to 8, so no subarray reaches 10.

Example 3

Input: nums = [6, 1, 1, 1, 12], target = 10

Output: 1

Explanation: 12 alone is already more than 10. The sum only has to reach target. It does not have to equal it.

Check your understanding

Work out the answer for this input before you write any code.

nums = [1, 2, 3, 4, 5], target = 11

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ target ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.