Quant Memo
Coding/●●●●●

Count subarrays that sum to k

Given an integer array nums (values may be negative) and a target k, count the number of contiguous subarrays whose elements sum to exactly k.

nums = [1, 1, 1], k = 2   ->  2      # [1,1] at (0,1) and (1,2)
nums = [1, -1, 0], k = 0  ->  3      # [1,-1], [0], [1,-1,0]

Target O(n)O(n) time. Sliding windows do not work here, negatives mean a window's sum is not monotonic.

Show a hint

Let P[i] be the prefix sum of the first i elements. A subarray (j, i] sums to k exactly when P[i] - P[j] = k, i.e. P[j] = P[i] - k. As you scan, how many earlier prefix sums equal P[i] - k?

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions