Home
DSA Patterns
Prefix Sum
Subarray Sum Equals K
Subarray Sum Equals K (LeetCode 560)
Subarray Sum Equals K (LeetCode 560): count the contiguous subarrays whose sum equals k in one pass, using a running prefix sum and a hash map of the sums seen so far.
Problem Understanding
Count the contiguous, non-empty subarrays of the integer array nums whose elements add up to exactly k.
Strategy (HashMap + Prefix Sum)
We want Sum(i, j) == k.
Since Sum(i, j) = Prefix[j] - Prefix[i-1], we want:Prefix[j] - Prefix[i-1] == k
=> Prefix[i-1] == Prefix[j] - k.
Algorithm:
Iterate through array, maintaining
current_sum.Check HashMap: how many times have we seen
current_sum - kbefore?Add that count to our answer.
Add
current_sumto the HashMap.
Interactive Visualization
K = 2
SEED MAP
nums
0
1
2
sum through i
0
1
2
Sum
0
Sum − k
:
Count
0
Map (sum:times seen)
Subarrays found here
None on this step
Count subarrays summing to 2. The map starts as {0: 1}: the empty prefix, so a subarray can start at index 0
Next
Add nums[0] = 1: running sum 1
Array
Target
Each step adds one number to the running sum and looks up how many earlier prefix sums equal sum - k. Every one of them starts a subarray that ends here; the figure outlines each match.
Edge Cases
Watch out for:
Negative Numbers: Prefix sums are not monotonic! Cannot use Sliding Window (Two Pointers). Must use HashMap.
k = 0: Subarrays with sum 0 are valid.
Zeroes: Multiple zeroes increase count significantly.
Dry Run
Nums: [1, 1, 1], k=2. Map: {0:1}. Count=0. sum=0.
| Num | New Sum | Check (Sum-k) | Map Has Check? | Action | Map Update |
|---|---|---|---|---|---|
| 1 | 1 | 1 - 2 = -1 | No | - | {0:1, 1:1} |
| 1 | 2 | 2 - 2 = 0 | Yes (val=1) | Count += 1 | {0:1, 1:1, 2:1} |
| 1 | 3 | 3 - 2 = 1 | Yes (val=1) | Count += 1 | {0:1, 1:1, 2:1, 3:1} |
Result: 2.
Solution
O(N) Time, O(N) Space.
Subarray Sum Equals K Code
1var subarraySum = function(nums, k) {2 let count = 0;3 let currSum = 0;4 const map = new Map();5 map.set(0, 1);67 for (const num of nums) {8 currSum += num;910 if (map.has(currSum - k)) {11 count += map.get(currSum - k);12 }1314 map.set(currSum, (map.get(currSum) || 0) + 1);15 }16 return count;17};
Subarray Sum Equals K in Python, Java, C++, TypeScript and C
Subarray Sum Equals K in Python
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
curr_sum = 0
prefix_map = {0: 1} # Base case: sum 0 occurs once
for num in nums:
curr_sum += num
if (curr_sum - k) in prefix_map:
count += prefix_map[curr_sum - k]
prefix_map[curr_sum] = prefix_map.get(curr_sum, 0) + 1
return countSubarray Sum Equals K in Java
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int currSum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int num : nums) {
currSum += num;
if (map.containsKey(currSum - k)) {
count += map.get(currSum - k);
}
map.put(currSum, map.getOrDefault(currSum, 0) + 1);
}
return count;
}
}Subarray Sum Equals K in C++
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int count = 0;
int currSum = 0;
unordered_map<int, int> map;
map[0] = 1;
for (int num : nums) {
currSum += num;
if (map.count(currSum - k)) {
count += map[currSum - k];
}
map[currSum]++;
}
return count;
}
};Subarray Sum Equals K in TypeScript
function subarraySum(nums: number[], k: number): number {
let count = 0;
let currSum = 0;
const map = new Map<number, number>();
map.set(0, 1);
for (const num of nums) {
currSum += num;
if (map.has(currSum - k)) {
count += map.get(currSum - k)!;
}
map.set(currSum, (map.get(currSum) || 0) + 1);
}
return count;
};Subarray Sum Equals K in C
typedef struct {
int key;
int val;
UT_hash_handle hh; // Requires uthash.h, standard in LeetCode environment
} HashEntry;
int subarraySum(int* nums, int numsSize, int k) {
int count = 0;
int currSum = 0;
HashEntry* map = NULL;
// Base case: map[0] = 1
HashEntry* entry = (HashEntry*)malloc(sizeof(HashEntry));
entry->key = 0;
entry->val = 1;
HASH_ADD_INT(map, key, entry);
for(int i=0; i<numsSize; i++) {
currSum += nums[i];
int target = currSum - k;
HashEntry* t;
HASH_FIND_INT(map, &target, t);
if(t) {
count += t->val;
}
HASH_FIND_INT(map, &currSum, t);
if(t) {
t->val++;
} else {
t = (HashEntry*)malloc(sizeof(HashEntry));
t->key = currSum;
t->val = 1;
HASH_ADD_INT(map, key, t);
}
}
// Cleanup simple for this snippet, real world needs HASH_ITER to free
return count;
}More practice: DSA interview questions with answers · patterns cheat sheet
