Skip to content

Subarray Sum Equals K

LeetCode

01 · Question

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals k.

02 · Solution

Reference solution

1def subarraySum(nums: List[int], k: int) -> int:
2 count = {0: 1}
3 pref = 0
4 res = 0
5
6 for x in nums:
7 pref += x
8 need = pref - k
9 res += count.get(need, 0)
10 count[pref] = count.get(pref, 0) + 1
11
12 return res