Problem
Count the contiguous subarrays whose elements add up to exactly k.
Original: LeetCode 560: Subarray Sum Equals K.
Examples
Example 1
`nums = [1, 1, 1], k = 2``2`Example 2
`nums = [1, 2, 3], k = 3``2`Example 3
`nums = [1, -1, 0], k = 0``3`Constraints
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
Hints
Hint 1
"Count", not "find one". Values can be negative, which is the key detail.
Hint 2
sum(i..j) = prefix[j] − prefix[i−1]. A target sum with negative values means prefix sum plus hash map, because the sliding-window shrink rule only works for non-negative values.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Fix each start and extend the end while keeping a running sum: O(n²).
Optimal. count.put(0, 1). For each x: sum += x, ans += count.getOrDefault(sum - k, 0), then count.merge(sum, 1, Integer::sum).
Alternative. For non-negative values only, a variable sliding window works in O(1) space.
Complexity
- Time
- O(n)
O(n) expected time and O(n) space.
- Space
- O(n)
Code
import java.util.HashMap;
public class SubarraySumK {
static int subarraySum(int[] nums, int k) {
var count = new HashMap<Integer, Integer>(); // prefix sum -> occurrences
count.put(0, 1);
int sum = 0, ans = 0;
for (int x : nums) {
sum += x;
ans += count.getOrDefault(sum - k, 0);
count.merge(sum, 1, Integer::sum);
}
return ans;
}
public static void main(String[] args) {
System.out.println(subarraySum(new int[] {1, 1, 1}, 2)); // 2
System.out.println(subarraySum(new int[] {1, 2, 3}, 3)); // 2
System.out.println(subarraySum(new int[] {1, -1, 0}, 0)); // 3
}
}Edge cases
- k = 0 with zeros and negative values: [1,-1,0] has three subarrays.
- A subarray that starts at index 0: the initial
put(0, 1)covers it.
Follow-ups
- Return true or false only (one variant reported in a Meta onsite on LeetCode Discuss): stop at the first hit.
- Subarray sum divisible by k: key on the remainder.
- Longest subarray with sum k: store the first index of each prefix instead of a count.
Interview script
"A sliding window fails because of negative numbers. Instead, I keep prefix sums: a subarray ending here sums to k exactly when some earlier prefix equals sum minus k. A hash map counts earlier prefixes, seeded with zero once. O(n) time and space."
Source: LeetCode 560: Subarray Sum Equals K Source: Java SE 17 API: Map.merge) Source: LeetCode Discuss: Meta E4 interview experience (candidate report, March 2025)
Sources (3)
- LeetCode 560: Subarray Sum Equals Kleetcode.com
- Java SE 17 API: Map.mergedocs.oracle.com
- LeetCode Discuss: Meta E4 interview experience (candidate report, March 2025)leetcode.com