Problem 34
Subarray Sum Equals K
Medium · 20 pts · Array, Hash Table, Prefix Sum
Problem
You are given an array of N integers and an integer K. Count how many non-empty blocks of consecutive elements (subarrays) have a sum of exactly K. Subarrays at different positions count separately, even if they contain the same values. The elements can be negative, so a sliding window does not work. Use prefix sums instead: a subarray from i + 1 to j sums to K exactly when prefix[j] - prefix[i] = K. While scanning, keep a hash map counting how often each prefix sum has occurred, and add the count of prefix[j] - K at every step.
Input
First line: integers N and K. Second line: N space-separated integers.
Output
Print the number of subarrays with sum K.
Constraints
1 <= N <= 20000; -1000 <= A[i] <= 1000; -10000000 <= K <= 10000000
Example input
3 2 1 1 1
Example output
2
Explanation
In 1 1 1 with K = 2, the subarray made of the first two elements sums to 2, and so does the one made of the last two. The whole array sums to 3, so there are 2 subarrays.