Skip to content

Subarray Sum Equals K

Count the subarrays that add up to k, using running prefix sums and a hash map of their counts.

MediumPrefix Sums
Solve on LeetCode

The problem

You get an integer array nums and an integer k. Return how many contiguous, non-empty subarrays have a sum exactly equal to k. The numbers can be negative, zero or positive.

Input nums = [3, 4, 7, -2, 2], k = 7

Output 3

[3, 4], [7] and [7, -2, 2] each add up to 7.

Input nums = [1, -1, 0], k = 0

Output 3

[1, -1], [0] and [1, -1, 0] all add up to 0.

Key constraint: Numbers can be negative, so a sliding window doesn't work: adding an element can make the sum smaller.

How to spot the pattern

  • You are counting contiguous subarrays with an exact sum.
  • Negative numbers rule out a sliding window, because growing a window doesn't always grow its sum.
  • Any subarray sum is the difference of two prefix sums, so you need to find matching earlier prefixes fast.

The idea

The sum of the subarray from i + 1 to j is prefix[j] - prefix[i]. So a subarray ending at j adds up to k exactly when some earlier prefix sum equals prefix[j] - k. Walk the array once, keep a hash map from each prefix sum to how many times it has appeared, and at each step add the count of prefix - k to the answer.

Brute force: Try every start and extend it to every end while keeping a running sum, which takes O(n^2) time.

Step by step

  1. 1Start the map with {0: 1}, standing for the empty prefix before the first element.
  2. 2Walk through the array, adding each number to a running sum prefix.
  3. 3Add count[prefix - k] (0 if missing) to the answer, since each earlier prefix with that value starts a subarray that ends here and sums to k.
  4. 4Then record the current prefix by adding 1 to count[prefix].
  5. 5Return the answer after the loop.

See the pattern move

The prefix sums pattern on a small example. Step through it, or press play.

Code

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        count = {0: 1}  # prefix sum -> how many times it has appeared
        prefix = 0
        answer = 0
        for num in nums:
            prefix += num
            answer += count.get(prefix - k, 0)
            count[prefix] = count.get(prefix, 0) + 1
        return answer

Complexity

Time

O(n)

Space

O(n)

One pass with O(1) average map work per number; the map holds up to n + 1 different prefix sums.

Watch out for

  • Forgetting the starting entry {0: 1}, which misses every subarray that begins at index 0.
  • Recording the current prefix before looking up prefix - k: with k = 0 each position then matches itself and counts an empty subarray.
  • Reaching for a sliding window, which only works when every number is positive.

Follow-up questions

What if all the numbers are positive?

Then a sliding window works with O(1) extra space: grow the right end, and shrink from the left while the sum is above k, counting each time it equals k.

How would you find the longest subarray with sum k instead?

Store the first index where each prefix sum appears instead of a count. At index j, if prefix - k was first seen at index i, the subarray from i + 1 to j is a candidate, and keeping the first index makes it as long as possible.

In Hinglish

Running sum rakho aur map mein har prefix sum ki ginti. Har step par dekho prefix - k kitni baar aaya hai; utne subarrays yahin khatam hote hain.

Related problems