Ctrl K

Stretches With an Exact Total

Medium
The array changes holds the daily changes of an account balance: a positive number is a deposit, a negative one is a withdrawal. An analyst wants periods of consecutive days over which the balance moved by exactly total (a negative total means it went down). Count the non-empty stretches of consecutive elements of changes whose sum equals total. Two stretches are different if they start or end at different positions.
Example 1
changes=[3, -1, 4, 0, 2], total=6 → 3

Three stretches add up to 6: [3, -1, 4], [3, -1, 4, 0] and [4, 0, 2]. Stretches with different boundaries count separately even if their sums match.

Example 2
changes=[0, 0, 0], total=0 → 6

Every stretch of zeros sums to 0: three of length 1, two of length 2 and one of length 3, which is 6 in all.

Example 3
changes=[5, -5, 5], total=5 → 3

The first [5], the last [5] and the whole array [5, -5, 5] fit. The stretches [5, -5] and [-5, 5] sum to 0.

Constraints
  • 1 ≤ changes.length ≤ 2 · 10⁴
  • -1000 ≤ changes[i] ≤ 1000
  • -10⁷ ≤ total ≤ 10⁷
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Run with a Given Sum MediumA Stretch Divisible by k MediumAs Many Heads as Tails MediumWindows With an Exact Alarm Count MediumWindows With a Divisible Sum Medium
loading Python…
Input
changes=[3, -1, 4, 0, 2], total=6
Expected
3

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