Count the contiguous pieces of a list that add up to exactly k. The list can contain negative numbers and zeros.
What to build
A program that counts the contiguous subarrays whose sum is k.
Requirements
- Count every contiguous subarray (different positions count separately, even if the values match).
- Do it in O(n) time with a dictionary of prefix sums.
Input
The first line has n and k. The second line has the n integers.
Output
The number of subarrays with sum k.
Constraints
1 ≤ n ≤ 10⁵; numbers and k between -10⁴ and 10⁴.
Example
Input:
3 2
1 1 1
Output:
2
Why it works
A subarray from i to j has sum prefix[j+1] − prefix[i]. For each j we count the earlier prefixes equal to prefix[j+1] − k, which a dictionary of prefix counts gives in O(1), so all subarrays are counted in one pass.
Examples
3 2 1 1 1
2
4 3 1 2 1 -1
3
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Let prefix be the running total. A subarray ending here has sum k when an earlier prefix equals prefix − k.
Hint 2
Keep a dictionary: prefix value → how many times it has occurred. Start it with {0: 1}.
Hint 3
Negative numbers are allowed, so a sliding window does not work; the dictionary does.
Solution
Show one correct solution (try it yourself first)
n, k = map(int, input().split())
nums = list(map(int, input().split()))
count = {0: 1}
total = 0
answer = 0
for x in nums:
total += x
answer += count.get(total - k, 0)
count[total] = count.get(total, 0) + 1
print(answer)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step