Shortest Stretch Over a Target

EasySliding Window≈ 20 min

You are given a list of positive integers nums and a number target. Find the shortest stretch of numbers in a row whose total is at least target, and return how many numbers it holds. If no stretch reaches the target, return 0.

Examples

text
nums = [2, 3, 1, 2, 4, 3], target = 7               →  2
nums = [1, 4, 4], target = 4                        →  1
nums = [1, 1, 1, 1], target = 9                     →  0
nums = [5, 1, 3, 5, 10, 7, 4, 9, 2, 8], target = 15 →  2

In the first example 4 + 3 = 7, two numbers. In the third, even all four numbers together add up to only 4.

Constraints

  • Between 0 and 20,000 numbers, each between 1 and 10,000; target is between 1 and 1,000,000,000.
  • Aim for O(n): each number should enter and leave a window at most once.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.