Two pointers and sliding window · Problem 2 of 3

Shortest stretch of days that reaches a goal

Pattern: Minimum Size Subarray Sum: Sliding Window

mediumNot solved yet

The problem

A fitness app stores how many thousand steps someone walked each day. Every value is positive. Write a function that returns the length of the shortest run of consecutive days whose total is at least goal. If no run reaches the goal, return 0.

text
1shortest_stretch([2, 3, 1, 2, 4, 3], 7)  ->  2
2shortest_stretch([1, 4, 4], 4)           ->  1
3shortest_stretch([1, 1, 1], 5)           ->  0
Example 1
2
0
3
1
1
2
2
3
4
4
3
5

4 + 3 reaches 7 in two days.

In the first example, [4, 3] adds up to 7 in two days. No single day reaches 7.

Write shortest_stretch(steps, goal) in Python or shortestStretch(steps, goal) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 20 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.