← All coding problems
Subarray Sum Equals K
mediumArrays & Hashing+20 XPTime limit 2s
Count the contiguous, non-empty subarrays whose sum is exactly k. Numbers can be negative.
Input:
- line 1:
n k - line 2:
nintegers
Output: the number of such subarrays (it may need a 64-bit integer).
Constraints: 1 ≤ n ≤ 10⁵, −1000 ≤ a[i] ≤ 1000, −10⁷ ≤ k ≤ 10⁷.
Think about it: the sum of a[i..j] is prefix[j] − prefix[i−1]. Keep a hash map of how many times each prefix sum has appeared. (A sliding window does not work here — why?)
Sample input 1
3 2 1 1 1
Sample output 1
2
Sample input 2
3 3 1 2 3
Sample output 2
2
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).