Browse curriculum

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 - k before?

  • Add that count to our answer.

  • Add current_sum to the HashMap.

Interactive Visualization

K = 2

SEED MAP

nums

1

0

1

1

1

2

sum through i

-

0

-

1

-

2

Sum

0

Sum − k

:

Count

0

Map (sum:times seen)

0:1

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

Free preview: the first 4 of 11 steps

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);
6
7 for (const num of nums) {
8 currSum += num;
9
10 if (map.has(currSum - k)) {
11 count += map.get(currSum - k);
12 }
13
14 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 count
Subarray 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

The approach, step by step

  1. Seed the map

    Start with count = 0, sum = 0 and a map {0: 1}.

  2. Extend the running sum

    Add each number to sum, then add map[sum - k] to the count if it exists.

  3. Record the sum

    Increment map[sum], and return the count after the last number.

Frequently asked questions

How does the hash map solve Subarray Sum Equals K?

A subarray from j to i sums to k exactly when the prefix sum before j equals the running sum at i minus k. The map counts how many times each prefix sum has appeared, so each step adds all such subarrays at once.


Why does the map start with {0: 1}?

It stands for the empty prefix before index 0. Without it, a subarray that starts at the first element and sums to k would never be counted.


Why can't a sliding window solve Subarray Sum Equals K?

Negative numbers mean the running sum can go down as well as up, so moving a window's edges does not reliably increase or decrease the sum. The prefix-sum map works for any integers in O(N) time and O(N) space.

New to the technique behind this problem? Watch it run step by step:

Prefix Sum Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description