Algo-Sim › Arrays & Hashing

Subarray Sum Equals K

Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Count the contiguous subarrays whose sum is exactly k, negatives included, with prefix sums and a hash map.

Problem

Given an integer array nums and an integer k, count how many contiguous, non-empty subarrays add up to exactly k.

Constraints

Edge cases to test

Follow-up questions

Why not a sliding window?
With negatives, growing the window can lower the sum, so there is no rule for when to shrink. Prefix sums with a count map work for any sign: O(n) time and space.
What if every number is positive?
Then a sliding window works: shrink while the sum is over k. O(n) time and O(1) space.
What if you need the longest such subarray instead?
Store the first index of each prefix sum, and at each i check i − first[sum − k]: O(n).

Solution

Java

public int subarraySum(int[] nums, int k) {
    Map<Integer, Integer> count = new HashMap<>();
    count.put(0, 1);
    int prefix = 0, result = 0;
    for (int x : nums) {
        prefix += x;
        result += count.getOrDefault(prefix - k, 0);
        count.merge(prefix, 1, Integer::sum);
    }
    return result;
}

Python

def subarray_sum(nums, k):
    count = {0: 1}
    prefix = result = 0
    for x in nums:
        prefix += x
        result += count.get(prefix - k, 0)
        count[prefix] = count.get(prefix, 0) + 1
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int subarraySum(vector<int> &nums, int k) {
        unordered_map<int, int> count = {};
        count[0] = 1;
        int prefix = 0, result = 0;
        for (int x : nums) {
            prefix += x;
            result += (count.count(prefix - k) ? count[prefix - k] : 0);
            count[prefix] += 1;
        }
        return result;
    }
};

More Arrays & Hashing problems