Net Climb Stretches

Hardprefix sumsAlso known as Subarray Sum Equals K

A cycling app splits every ride into kilometres and records the net change in height over each one: +40 for a kilometre that climbs 40 metres, -15 for one that drops 15. This month's challenge pays out a badge for every stretch of back-to-back kilometres whose net climb is exactly the height of a famous tower.

Stretches can overlap, and any stretch of one or more kilometres counts. The app needs to know how many badges your ride earned.

Your task

Write countStretches(changes, k). Return how many pairs of indexes i ≤ j there are such that changes[i] + changes[i + 1] + ... + changes[j] === k.

Changes and k can be negative or zero. An empty ride has no stretches, so it returns 0.

countStretches(changes: int[], k: int) → int

Examples

Example 1
Input
changes = [2, 3, -1, 1, 4]
k = 5
Output
3
Why

Three stretches add up to 5: kilometres 0 to 1 (2 + 3), kilometres 0 to 3 (2 + 3 - 1 + 1) and kilometres 3 to 4 (1 + 4). The first two overlap, and both count.

Example 2
Input
changes = [4, -4, 4]
k = 0
Output
2
Why

A climb and a matching drop cancel out. Kilometres 0 to 1 and kilometres 1 to 2 both have a net change of 0, so the answer is 2.

Constraints

  • 0 ≤ changes.length ≤ 20,000
  • -1,000 ≤ changes[i] ≤ 1,000
  • -10,000,000 ≤ k ≤ 10,000,000
Start with brute force

Try every start i, and from it extend the end j one kilometre at a time, keeping a running total. Count every time the total equals k.

That is n(n + 1)/2 stretches, about 200 million for a 20,000 km log. A sliding window does not rescue it: with descents the total can go down as the window grows, so you can never tell whether to grow or shrink it.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code