Subarray Sum Equals K

Medium

Topics
ArrayHash TablePrefix Sum

Given an integer array nums and an integer k (passed as target), return the total number of contiguous subarrays whose sum equals k.

Example 1

101112sum = 2
The answer counts contiguous blocks whose values total 2; one of them is braced. Blocks may overlap and are counted separately, and because the values can be negative a longer block is not necessarily a larger sum. There are 2 such blocks here.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,1,1], k = 2
Output: 2

Example 2

102132sum = 3
Input:  nums = [1,2,3], k = 3
Output: 2

Constraints

  • 1 <= nums.length <= 2*10^4
  • -1000 <= nums[i] <= 1000
  • nums may contain negatives (sliding window will not work).
Editorial — intuition, approach, complexity and pitfalls

Intuition

A subarray sum equals prefix[j] - prefix[i]. We want that difference to be k, i.e. prefix[i] = prefix[j] - k.

So as we sweep and maintain a running prefix sum, we count how many earlier prefix sums equal current - k using a hash map. This handles negatives, which a sliding window cannot.

Approach

  1. Keep a map of prefix-sum → how many times it has occurred, seeded with {0: 1}.
  2. Maintain the running sum. Add count[sum - k] to the answer.
  3. Increment count[sum].

Walkthrough

nums = [1,1,1], k = 2
sum=1 need -1 -> 0; count{0:1,1:1}
sum=2 need 0 -> +1; count{...2:1}
sum=3 need 1 -> +1  total = 2

Complexity

  • Time — O(n): one pass with O(1) map operations.
  • Space — O(n): the prefix-sum frequency map.

Common Pitfalls

  • Seed the map with {0:1} so subarrays starting at index 0 are counted.

Full Solution — all languages

class Solution:
    def subarraySum(self, nums, target):
        from collections import defaultdict
        cnt = defaultdict(int)
        cnt[0] = 1
        s = res = 0
        for x in nums:
            s += x
            res += cnt[s - target]
            cnt[s] += 1
        return res
SensAI
Beta
Tap the mic to stop voice mode