Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 560 Subarray Sum Equals K - Walkthrough

HashMap technique trace

Count subarrays summing to k=3k=3 in arr=[1,2,1,2,1]arr = [1, 2, 1, 2, 1]. Use prefix sums with a hashmap. As you compute prefix sums, track how many times each sum occurred.

At each position, add count[prefixk]count[prefix - k] to the answer. Prefix sums: 0,1,3,4,6,70, 1, 3, 4, 6, 7. At sum 33: count[0]=1count[0] = 1, add 11. At sum 44: count[1]=1count[1] = 1, add 11. At sum 66: count[3]=1count[3] = 1, add 11. At sum 77: count[4]=1count[4] = 1, add 11. Total: 44 subarrays. They are: [1,2][1,2], [2,1][2,1], [1,2][1,2], [2,1][2,1].