Subarray Sum Equals K
Medium
Topics
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
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
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
- Keep a map of prefix-sum → how many times it has occurred, seeded with
{0: 1}. - Maintain the running sum. Add
count[sum - k]to the answer. - 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 = 2Complexity
- 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 resimport java.util.*;
class Solution {
public int subarraySum(int[] nums, int target) {
Map<Integer,Integer> cnt = new HashMap<>();
cnt.put(0, 1);
int s = 0, res = 0;
for (int x : nums) {
s += x;
res += cnt.getOrDefault(s - target, 0);
cnt.merge(s, 1, Integer::sum);
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int subarraySum(vector<int>& nums, int target) {
unordered_map<int,int> cnt;
cnt[0] = 1;
int s = 0, res = 0;
for (int x : nums) {
s += x;
if (cnt.count(s - target)) res += cnt[s - target];
cnt[s]++;
}
return res;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var subarraySum = function(nums, target) {
const cnt = new Map();
cnt.set(0, 1);
let s = 0, res = 0;
for (const x of nums) {
s += x;
res += cnt.get(s - target) || 0;
cnt.set(s, (cnt.get(s) || 0) + 1);
}
return res;
};