Subarray Sum Equals K
Signals to notice
Brute force first
Check every subarray sum. Each subarray independently summed. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Prefix sums + hash map: for each position, compute the prefix sum. If prefixSum - k exists in the map, that many subarrays ending here sum to k. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
What must stay true
sum(i.j) = prefixSum[j] - prefixSum[i-1]. If prefixSum[j] - k = prefixSum[i-1], then the subarray from i to j sums to k. The hash map counts how many previous prefix sums equal prefixSum[j] - k. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Easy way to go wrong
Trying sliding window — that only works for positive numbers. With negatives or zeros, use prefix sums. Also, initialize the map with {0: 1} for subarrays starting at index 0. The fix is usually to return to the meaning of each move, not just the steps themselves.