Subarray Sum Equals K
Subarray Sum Equals K is basically a counting game: from an array nums, how many contiguous chunks add up exactly to k? You only return the count, not the chunks themselves.
The trick that makes this fast is prefix sum + frequency map. As you scan the array, keep a running total called prefix. At any position, if you already saw a prefix value of prefix - k, it means there is a valid subarray ending here. So you add that frequency to the answer.
Workflow is simple: check how many times prefix - k appeared, add it to result, then record the current prefix in the map. Start with freq[0] = 1 so subarrays starting from index 0 are counted correctly.
This works smoothly even with negative numbers and zeros, where two-pointer sliding window usually breaks. It is O(n) time, and it naturally handles overlapping subarrays too. The judge cases include mixed-sign arrays and lots of zero-based overlaps, so counting prefix frequencies (not just storing one index) is the key to getting the correct final number.
One small but important detail: the order is always read first, write second. If you store current prefix too early, you can accidentally count an invalid zero-length subarray. Keep that sequence clean, and this solution stays both fast and reliable on all judge tests.
Examples
Subarrays [1,1] at positions (0,1) and (1,2).
Subarrays [1,2] and [3].
Subarrays [1,-1], [0], and [1,-1,0].
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int subarray_sum_equals_k(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
count.put(0, 1);
int s = 0, ans = 0;
for (int x : nums) {
s += x;
ans += count.getOrDefault(s - k, 0);
count.put(s, count.getOrDefault(s, 0) + 1);
}
return ans;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
