560. Subarray Sum Equals K
https://leetcode.com/problems/subarray-sum-equals-k/
Python
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
# Key as the total, value is the count of this total
sum_map = defaultdict(lambda: 0)
# counter to accumulate the answer
count = 0
# The current sum
total = 0
# Edge case, total == 0 initial with one possible combination: []
sum_map[0] = 1
for num in nums:
total += num
count += sum_map[total-k]
sum_map[total] += 1
return count