Stretches That Add Up

MediumRunning Totals≈ 30 min

You are given a list of integers nums, which may be negative, and a target. Count the stretches of numbers in a row, at least one number long, whose total is exactly target. Stretches that overlap, or that contain one another, are counted separately.

Examples

text
nums = [1, 1, 1], target = 2                      →  2
nums = [3, 4, -7, 3, 1, 3, 1, -4], target = 7     →  3
nums = [1, 2, 3], target = 7                      →  0
nums = [0, 0, 0], target = 0                      →  6

In the first example the two stretches are the first two 1s and the last two. In the second they are [3, 4], [3, 1, 3], and [3, 4, -7, 3, 1, 3], which contains the other two. In the last, every one of the six stretches of [0, 0, 0] adds up to 0.

Constraints

  • Between 0 and 20,000 numbers, each between -1,000 and 1,000.
  • Aim for O(n). The numbers can be negative, so a sliding window does not work here.
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.