Subarray Sum Equals K Problem
Description
LeetCode Problem 560. Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
Example:
Input: nums = [1, 2, 3], k = 3
Output: 2
Solution
Approach: Prefix Sums and a Hash Map
Checking every subarray takes O(n2) time. Prefix sums let us count all subarrays that end at a given index in O(1).
Let prefix(j) be the sum of nums[0] through nums[j], and prefix(-1) = 0 for the empty prefix. The subarray from i + 1 to j sums to prefix(j) - prefix(i). So it equals k exactly when
prefix(i) = prefix(j) - k
That means the number of good subarrays ending at j is the number of earlier prefixes whose sum is prefix(j) - k. We keep those counts in a hash map while walking the array:
- Start with
prefixCount = {0: 1}. This is the empty prefix, which stands for subarrays that start at index 0. - For each number, add it to
prefix. - Add
prefixCount[prefix - k]to the answer. - Then record the current prefix:
prefixCount[prefix] += 1.
Two details matter. Step 3 comes before step 4, so a prefix is never paired with itself; with k = 0 that would count empty subarrays. And numbers can be negative, so a sliding window does not work here: growing the window does not always increase the sum.
For nums = [1, 2, 3], k = 3 the prefixes are 1, 3, 6. At 3 we find the empty prefix 0 (subarray [1, 2]), and at 6 we find the prefix 3 (subarray [3]): 2 in total.
Complexity: O(n) time and O(n) space for the hash map, where n is the length of nums.
import collections
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
prefix_count = collections.defaultdict(int) # prefix sum -> how many prefixes have it
prefix_count[0] = 1 # the empty prefix, so subarrays starting at index 0 are counted
prefix = 0
count = 0
for x in nums:
prefix += x
# A subarray ending here sums to k when an earlier prefix equals prefix - k.
count += prefix_count[prefix - k]
prefix_count[prefix] += 1
return count
Now write it from memory
Close the write-up and solve it yourself against the tests.