Subarray Sum Equals K

Pattern: Prefix sums and difference arrays

medium

Count subarrays summing to k in one pass, by counting how many earlier running sums equal the current running sum minus k.

The problem

You are given an array nums of whole numbers (which may be negative) and a target k. Return how many contiguous, non-empty subarrays add up to exactly k. For example, [1, 1, 1] with k = 2 has two such subarrays.

The function name subarraySum matches LeetCode. Use the link above for the exact statement.

Think first

  • How many subarrays does an array of length n have? How long does checking them all take?
  • A subarray ending at index i sums to k. What must be true about the running sum just before it starts?
  • If that earlier running sum appeared three times, how many subarrays ending at i sum to k?

Hints

    Brute force, and why it fails

    For every start, extend the end one step at a time with a running sum and count matches: O(n²). That is about 2 × 10⁸ steps at LeetCode's limits, which is borderline. With negatives, a sliding window cannot be used.

    The key insight

    Every subarray sum is a difference of two running sums. Counting earlier running sums in a hash map turns the pair search into one look-up per position.

    Dry run

    10 
    11 
    12 
    prefix0
    count0
    seen{0: 1}

    nums = [1, 1, 1] and k = 2. The map counts how often each running sum has appeared. It starts with the empty prefix, sum 0, once.

    Step 1 of 4

    The plan

    seen = {0: 1}
    prefix = 0
    count = 0
    for x in nums:
        prefix = prefix + x
        count = count + seen[prefix - k]      # 0 if missing
        seen[prefix] = seen[prefix] + 1
    return count
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One pass with average O(1) map operations. The map holds up to n + 1 distinct running sums.

    Edge cases

    • k = 0 with zeros, as in [0, 0, 0]: every subarray counts, which makes 6.
    • Negative numbers, as in [1, -1, 1, -1] with k = 0: 4.
    • No match: 0.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int subarraySum(int[] nums, int k) {
            Map<Integer, Integer> seen = new HashMap<>();      // prefix sum -> how many times it has appeared
            seen.put(0, 1);                                    // the empty prefix
            int prefix = 0;
            int count = 0;
            for (int x : nums) {
                prefix += x;
                count += seen.getOrDefault(prefix - k, 0);     // each earlier prefix of (prefix - k) starts one subarray
                seen.put(prefix, seen.getOrDefault(prefix, 0) + 1);
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            unordered_map<int, int> seen;                      // prefix sum -> how many times it has appeared
            seen[0] = 1;                                       // the empty prefix
            int prefix = 0;
            int count = 0;
            for (int x : nums) {
                prefix += x;
                auto found = seen.find(prefix - k);            // each earlier prefix of (prefix - k) starts one subarray
                if (found != seen.end()) {
                    count += found->second;
                }
                seen[prefix]++;
            }
            return count;
        }
    };

    Python

    class Solution:
        def subarraySum(self, nums: list[int], k: int) -> int:
            seen = {0: 1}                           # prefix sum -> how many times it has appeared; the empty prefix
            prefix = 0
            count = 0
            for x in nums:
                prefix += x
                count += seen.get(prefix - k, 0)    # each earlier prefix of (prefix - k) starts one subarray
                seen[prefix] = seen.get(prefix, 0) + 1
            return count

    Common mistakes

    • Adding the current running sum to the map before looking up, which counts an empty subarray when k = 0.
    • Starting the map empty instead of {0: 1}.
    • Trying a sliding window, which fails with negative numbers.

    Similar problems