Subarray Sum Equals K
Given an array of integers nums and an integer k, return how many contiguous, non-empty subarrays add up to exactly k.
Example 1
Input: nums = [1, 1, 1], k = 2 Output: 2
[1, 1] appears twice: at positions 0 to 1 and 1 to 2.
Example 2
Input: nums = [1, 2, 3], k = 3 Output: 2
Both [1, 2] and [3] add up to 3.
Constraints
1 <= nums.length <= 20000-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
Approach
Checking every subarray takes O(n²) time. A sliding window doesn't help here, because negative numbers and zeros mean that growing the window can lower the sum and shrinking it can raise it.
Running totals solve it in one pass. If prefix is the sum of everything up to the current element, then a subarray ending here adds up to k exactly when some earlier running total equals prefix - k. So keep a hash map that counts how many times each running total has appeared. At each element, add the count for prefix - k to the answer, then record the current total. Seeding the map with {0: 1} covers subarrays that start at index 0.
Steps
- Create a map
seen = {0: 1}and setprefixandcountto0. - For each number, add it to
prefix. - Add
seen[prefix - k](or 0) tocount. - Increase
seen[prefix]by 1. Returncountat the end.
from typing import List
def subarray_sum(nums: List[int], k: int) -> int:
seen = {0: 1} # prefix sum -> how many times it has appeared; the empty prefix sums to 0
prefix = 0
count = 0
for num in nums:
prefix += num
count += seen.get(prefix - k, 0) # earlier prefixes that leave exactly k
seen[prefix] = seen.get(prefix, 0) + 1
return countComplexity
- Time:
O(n). Each element does constant work with the hash map. - Space:
O(n)for the map of running totals.
Common mistakes
- Leaving out the
{0: 1}entry. Subarrays that start at index 0 are never counted without it. - Recording the current total before looking up
prefix - k. Whenkis 0, that counts an empty subarray. - Using a sliding window. It only works when every number is positive.