Subarray Sum Equals K
Recognize the pattern
Brute force idea
A straightforward first read of Subarray Sum Equals K is this: 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.
Better approach
A calmer way to see Subarray Sum Equals K is this: 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.
Key invariant
The truth you want to protect throughout Subarray Sum Equals K is this: 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.
Watch out for
One easy way to drift off course in Subarray Sum Equals K is this: 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.