Ctrl K

Shortest Stretch to the Goal

Medium
A runner keeps a log: steps[i] is how many kilometres they ran on day i, and every value is positive. The coach wants the shortest run of consecutive days that adds up to at least goal kilometres. Return the length of that run in days. If even all the days together fall short of goal, return 0. Once you have an O(n) solution, try finding an O(n log n) one as well.
Example 1
goal=10, steps=[3, 1, 6, 2, 5, 4] → 3

The consecutive days [6, 2, 5] give 13 ≥ 10, which is 3 days. No two neighbouring days are enough: the best pair is 5 + 4 = 9.

Example 2
goal=8, steps=[2, 9, 1] → 1

The single day with 9 is already enough.

Example 3
goal=20, steps=[4, 4, 4] → 0

Even all days together give only 12, so the answer is 0.

Constraints
  • 1 ≤ goal ≤ 10^9
  • 1 ≤ steps.length ≤ 10^5
  • 1 ≤ steps[i] ≤ 10^4
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWindows With a Small Product MediumLongest Run of Ones With k Fixes MediumTrim the Ends to a Target MediumEven Out With Increments MediumRug Over Painted Stretches Medium
loading Python…
Input
goal=10, steps=[3, 1, 6, 2, 5, 4]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 75 tests on the server, hidden ones included.