PythonMediumHashing20 min
Count subarrays with a target sum
Values may be negative or zero. Count all index ranges separately, even when they contain identical values. Interviewers use this problem to assess count previous prefix sums rather than using a positive-only sliding window.
Input
First line: n and target. Second line: n integers.
Output
Print the result on one line; print an empty line for an empty string.
Constraints
0 <= n <= 100000; -10^9 <= values and target <= 10^9.
Example
Input
3 2 1 1 1
Output
2
Example 2 input
3 -3 -1 -2 -3
Output
2
Negative targets and negative numbers are supported.
Public test cases (2)
Input
3 2 1 1 1
Expected output
2
Input
5 0 1 -1 0 1 -1
Expected output
7
Hints (2)
- Identify the state needed to avoid repeated work.
- Count previous prefix sums rather than using a positive-only sliding window.
Target complexity: time O(n) expected · space O(n)
