DSA Factory
Free Arrays lessonsArrays · Stage 7 · Prefix sums · Step 4

Count stretches that hit k

Count every run of numbers that adds up to k, with a map of running totals. About 10 minutes.

Look up the partner total

You want stretches that add up to exactly k. A stretch ending here adds up to k when the running total now, minus the running total just before the stretch started, is k. So the total you're looking for back in the past is: now minus k.

That's the two-sum idea again: instead of searching, keep the totals you've seen in a map and look up the partner.

Partner total: the total now, minus k.
k = 2 · totals 1, 2, 3
1
0
1
1
1
2
i

total 1. Partner 1 − 2 = −1: seen 0 times. Store 1.

Move 1 of 3

Count partners, don't just find one

Several earlier positions can have the same running total, and each one starts a different stretch. So the map counts how many times you've seen each total, and you add that count.

Two details: start the map with the total 0 seen once (the empty start before the first box), and look up before you store the current total. Otherwise, when k is 0, an empty stretch would sneak into the count.

Start with 0, seen once: the empty start.
Look up, then store: or empty stretches get counted.
In code
seen = {0: 1}
total = count = 0
for x in nums:
    total += x
    count += seen.get(total - k, 0)
    seen[total] = seen.get(total, 0) + 1
return count
Quick check

k is 3. The running total is 10, and the map says the total 7 was seen twice. How many stretches ending here add up to 3?

  1. A2
  2. B1
  3. C10
Show the answer

2. Each earlier total of 7 starts a stretch that adds 10 − 7 = 3.

Your problem

Stretches that sum to k

You get a list of numbers (possibly negative) and a target k. Count the non-empty runs of consecutive numbers that add up to exactly k, and return the count.

Example
nums = [1, 2, 3], k = 3 → 2

0 ≤ n ≤ 1,000,000 · −1,000 ≤ each value ≤ 10^6 · the count can pass 2^31: return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve