Arrays and hashing · Problem 3 of 3

Count the stretches that hit a sales target

Pattern: Count Subarrays That Sum to K

mediumNot solved yet

The problem

A shop records its net sales for each day. Refunds can make a day's number negative. Write a function that counts how many stretches of consecutive days have sales that add up to exactly target.

A stretch is one or more days in a row. Two stretches are different if they start or end on different days.

text
1count_target_stretches([3, 4, 7, -2, 2], 7)  ->  3
2count_target_stretches([1, 1, 1], 2)         ->  2
3count_target_stretches([0, 0], 0)            ->  3
The stretches that add up to 71 / 3
3
0
4
1
7
2
-2
3
2
4

3 + 4 = 7

In the first example, the stretches are [3, 4], [7] and [7, -2, 2]. In the third, each single day sums to 0, and so do both days together.

Write count_target_stretches(daily, target) in Python or countTargetStretches(daily, target) 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.