Dynamic Programming21 sections · 915 units
Open in Course

LeetCode 560 Subarray Sum Equals K - HashMap Trick

Count with frequency

Here's the observation. If pref[j]−pref[i]=kpref[j] - pref[i] = k, then the subarray from i+1i+1 to jj sums to kk. Rearrange: pref[j]−k=pref[i]pref[j] - k = pref[i]. So for each position jj, you need to count how many earlier prefix sums equal pref[j]−kpref[j] - k. Use a HashMap to store prefix sum frequencies. As you iterate:

1.1. Check if (pref[j]−k)(pref[j] - k) exists in the map. Add that count to your answer.

2.2. Add current pref[j]pref[j] to the map. One pass. O(n)O(n) time, O(n)O(n) space. This pattern appears in many problems.