Net Climb Stretches

Hardprefix sumsAlso known as Subarray Sum Equals K

A cycling app splits each ride into kilometres and records each one's net height change: +40 for a kilometre that climbs 40 metres, -15 for one that drops 15. This month's challenge awards 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. How many badges did your ride earn?

Your task

Write countStretches(changes, k). Return how many index pairs i ≤ j satisfy changes[i] + changes[i + 1] + ... + changes[j] === k.

Changes and k can be negative or zero. An empty ride 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), 0 to 3 (2 + 3 - 1 + 1) and 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. Kilometres 0 to 1 and 1 to 2 both net 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

For every start i, extend the end j one kilometre at a time with a running total, counting each time it equals k.

That is n(n + 1)/2 stretches, about 200 million for a 20,000 km log. A sliding window cannot help: with descents the total can drop as the window grows, so you never know 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