Subarray Sum Equals K (LeetCode 560): Solution and Explanation

Medium
Array
Hash Table
Prefix Sum

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Initialize prefix_count = {0: 1}, curr_sum = 0 and count = 0.
  2. For each number, add it to curr_sum.
  3. Compute diff = curr_sum - k. Every earlier prefix equal to diff marks the start of a subarray ending here that sums to k.
  4. If diff is in the map, add prefix_count[diff] to count.
  5. Record the current prefix by incrementing prefix_count[curr_sum].
  6. Return count after the loop.

Step-by-step example

nums = [1,2,3], k = 3
  1. Start with prefix_count = {0:1}, curr_sum = 0, count = 0.
  2. num = 1: curr_sum = 1, diff = -2 is not in the map. Record 1: {0:1, 1:1}.
  3. num = 2: curr_sum = 3, diff = 0 appears once, so count = 1 (the subarray [1,2]). Record 3: {0:1, 1:1, 3:1}.
  4. num = 3: curr_sum = 6, diff = 3 appears once, so count = 2 (the subarray [3]). Record 6.
  5. 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 count

Time and space complexity

Time

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.

Space

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_sum before looking up diff. 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.