Practice · Prefix sums · 1 of 2

Count Runs That Sum to k

You are given a list of integers nums and an integer k. Return how many non-empty subarrays (contiguous runs of positions) of nums add up to exactly k.

The numbers can be negative, so adding a number to a run can make its sum go down as well as up. Runs at different positions count separately, even when they hold the same numbers.

Example 1

Input
nums = [2, -1, 1, 3, -2], k = 3
Output
3
[3], [-1, 1, 3] and the whole list each add up to 3.

Example 2

Input
nums = [0, 0, 0], k = 0
Output
6
All six runs (three of length 1, two of length 2, one of length 3) add up to 0.

Constraints

  • nums holds 1 to 2 × 10⁴ numbers.
  • Every number is between −1000 and 1000.
  • k is between −10⁷ and 10⁷.
Brush up firstHash Table visualiser