Subarray Sum Equals K (LeetCode 560): Solution and Explanation
Given an integer array that may include negative numbers and an integer k, count how many contiguous, non-empty subarrays add up to exactly k.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force fixes a start index and extends to the right, keeping a running sum and counting each time it equals k. That is O(n²), which for twenty thousand elements means around two hundred million additions. It works, but it recomputes overlapping sums constantly.
A sliding window does not help here, even though it solves similar problems, because the array can contain negatives. Growing a window can make the sum go down, so there is no rule for when to shrink. The tool that does help is the prefix sum. If P[i] is the sum of the first i elements, the sum of the subarray between two positions is the difference of two prefix sums. A subarray ending at the current position sums to k exactly when some earlier prefix sum equals the current prefix sum minus k.
So while scanning left to right, keep a hash map from each prefix sum seen so far to how many times it has appeared. At each element, update the running sum, look up how many earlier prefixes equal curr_sum - k, and add that count to the answer. Then record the current prefix. The map starts with {0: 1} to represent the empty prefix, which lets subarrays that start at index 0 be counted. Each lookup asks, in effect, how many places could this subarray have started.
Approach: Prefix sums with a hash map of counts
- Initialize
prefix_count = {0: 1},curr_sum = 0andcount = 0. - For each number, add it to
curr_sum. - Compute
diff = curr_sum - k. Every earlier prefix equal todiffmarks the start of a subarray ending here that sums to k. - If
diffis in the map, addprefix_count[diff]tocount. - Record the current prefix by incrementing
prefix_count[curr_sum]. - Return
countafter the loop.
Step-by-step example
nums = [1,2,3], k = 3
- Start with
prefix_count = {0:1},curr_sum = 0,count = 0. - num = 1:
curr_sum = 1,diff = -2is not in the map. Record 1:{0:1, 1:1}. - num = 2:
curr_sum = 3,diff = 0appears once, socount = 1(the subarray [1,2]). Record 3:{0:1, 1:1, 3:1}. - num = 3:
curr_sum = 6,diff = 3appears once, socount = 2(the subarray [3]). Record 6. - Return 2.
Code: Python, Java, C++
1class Solution:
2 def subarraySum(self, nums: List[int], k: int) -> int:
3 prefix_count = {0: 1}
4 curr_sum = 0
5 count = 0
6 for i, num in enumerate(nums):
7 curr_sum += num
8 diff = curr_sum - k
9 if diff in prefix_count:
10 count += prefix_count[diff]
11 prefix_count[curr_sum] = prefix_count.get(curr_sum, 0) + 1
12 return count1class Solution {
2 public int subarraySum(int[] nums, int k) {
3 Map<Integer, Integer> prefixCount = new HashMap<>();
4 prefixCount.put(0, 1);
5 int sum = 0, count = 0;
6 for (int i = 0; i < nums.length; i++) {
7 sum += nums[i];
8 int diff = sum - k;
9 if (prefixCount.containsKey(diff)) {
10 count += prefixCount.get(diff);
11 }
12 prefixCount.put(sum, prefixCount.getOrDefault(sum, 0) + 1);
13 }
14 return count;
15 }
16}1class Solution {
2public:
3 int subarraySum(vector<int>& nums, int k) {
4 unordered_map<int, int> prefixCount;
5 prefixCount[0] = 1;
6 int sum = 0, count = 0;
7 for (int i = 0; i < nums.size(); i++) {
8 sum += nums[i];
9 int diff = sum - k;
10 if (prefixCount.count(diff)) {
11 count += prefixCount[diff];
12 }
13 prefixCount[sum]++;
14 }
15 return count;
16 }
17};Time and space complexity
O(n)
Each element triggers a constant number of hash map lookups and updates, which are O(1) on average. For twenty thousand elements that is a single quick pass.
O(n)
In the worst case every prefix sum is distinct, so the map stores n + 1 entries. When many prefix sums repeat, the map stays much smaller.
Other approaches
Brute force with running sums (time O(n²), space O(1))
For each start index, extend right while accumulating the sum and count matches. It uses no extra memory and is simple to verify, but it is quadratic.
Sliding window for non-negative input (time O(n), space O(1))
If every number were non-negative, two pointers could grow and shrink a window in linear time with constant memory. It does not apply to this problem because negative values break the shrinking rule.
Common mistakes
- Forgetting to seed the map with
{0: 1}, which misses every subarray that starts at index 0. - Recording
curr_sumbefore looking updiff. When k is 0 that would count an empty subarray ending at the current index. - Using a set instead of counts. The same prefix sum can occur several times, especially with zeros and negatives, and each occurrence is a separate subarray.
- Reaching for a sliding window because the problem looks like other subarray sum questions. Negative numbers make the window approach incorrect.
Frequently asked questions
Why does subarray sum equals k use prefix sums?
The sum of any subarray is the difference between two prefix sums. That turns the search for a subarray into a search for an earlier prefix equal to curr_sum - k, which a hash map answers in constant time.
Why can't I use a sliding window here?
A sliding window relies on the sum growing when the window grows and shrinking when it shrinks. With negative numbers that is not true, so you cannot decide when to move the left pointer.
Why is the map initialized with {0: 1}?
It represents the empty prefix before the first element. When the running sum itself equals k, diff is 0, and that entry counts the subarray from index 0 to the current position.
What is the time complexity of subarray sum equals k?
It is O(n) time on average because of constant-time hash map operations, and O(n) space for the map of prefix sums.