Subarray Sum Equals K

MediumPrefix Sum · Hash Map🧩 Prefix SumLeetCode #560 ↗Updated

Problem

Given an integer array nums (values may be negative) and an integer k, count how many contiguous, non-empty subarrays add up to exactly k.
Input[1,1,1], k=2Output2
Input[1,2,3], k=3Output2

1 ≤ n ≤ 2·104  ·  -1000 ≤ nums[i] ≤ 1000  ·  -107 ≤ k ≤ 107

Try it yourself

Java
class Solution {
    public int subarraySum(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A subarray (j..i] sums to k exactly when prefix[i] - prefix[j] = k, i.e. prefix[j] = prefix[i] - k. So while scanning, just ask: how many earlier prefixes equal sum - k?
PatternPrefix Sum

Instinct Repeated range-sum queries, or "count subarrays whose sum equals / divides K" with negatives allowed? Store running totals and subtract two of them.

Memory hack Any range is two prefixes apart - sum(i..j) = P[j+1] - P[i], so remember every P you've passed.

Open the Prefix Sum guide →

Approaches

Brute ForceEnumerate & Re-sum Every Subarray

Time O(n3)Space O(1)

Try every pair (start, end) and add up nums[start..end] from scratch with a third loop. Count the pairs whose sum equals k.

Java
public int subarraySum(int[] nums, int k) {
    int count = 0;
    for (int start = 0; start < nums.length; start++) {
        for (int end = start; end < nums.length; end++) {
            int sum = 0;
            for (int m = start; m <= end; m++) sum += nums[m];
            if (sum == k) count++;
        }
    }
    return count;
}

Obviously correct, but cubic — far too slow for n = 2·104.

At a glance

LevelApproachTimeSpace
Brute ForceEnumerate & Re-sum Every SubarrayO(n3)O(1)
BetterRunning Sum per StartO(n2)O(1)
OptimalPrefix Sum + Hash Map of CountsO(n)O(n)
Common pitfalls
  • Forgetting seen.put(0, 1) — misses subarrays that start at index 0.
  • Using a sliding window — fails with negative numbers.
  • Storing a boolean/index instead of a count — repeated prefixes each add a subarray.
Interview tips
  • Ask early whether values can be negative; it decides window vs. prefix map.
  • Write the identity prefix[i] - prefix[j] = k before coding.
  • Same template solves divisible-by-K and binary-subarray variants.
Pattern
Prefix sum + hash map → count/locate subarrays with a target sum when values can be negative.
My notes saved in this browser