← Back to Algorithms, page 1

algorithms-0010 · Medium mid

Subarray sum equals K: count the contiguous subarrays whose sum is exactly k, when the list may contain negative numbers.

A subarray nums[i..j] sums to k exactly when prefix(j + 1) - prefix(i) = k. Scan once, keep the running prefix sum and a dictionary counting how many times each earlier prefix sum appeared; at each step add the count of prefix - k. Start with {0: 1} for the empty prefix. O(n) time and space; a sliding window fails here because negatives break monotonicity.

Full answer

Problem

Given nums (may include negatives and zeros) and an integer k, return the number of contiguous subarrays whose sum equals k.

Example: nums = [1, 2, 3], k = 3 gives 2 ([1, 2] and [3]).

Constraints: 0 <= len(nums) <= 2 x 10^4, values from -1000 to 1000, k from -10^7 to 10^7.

Brute force

Fix each start, extend the end while keeping a running sum, count matches: O(n^2) time, O(1) space.

Why not a sliding window?

A window works when growing it always increases the sum (all positive values). With negatives, extending the window can lower the sum, so you cannot decide which side to move.

Optimal approach

Let prefix be the sum of everything so far. A subarray ending here sums to k when some earlier prefix equals prefix - k.

  1. seen = {0: 1} (the empty prefix, so subarrays starting at index 0 are counted).
  2. For each value: prefix += x; count += seen[prefix - k]; then seen[prefix] += 1.

Why it works

For each end position, the number of valid starts equals the number of earlier prefix sums equal to prefix - k, and the dictionary stores exactly those counts. Updating seen after counting stops a prefix from pairing with itself (which would count an empty subarray when k = 0).

Walk-through with [1, -1, 0], k = 0: prefixes are 0 (start), 1, 0, 0. At the second element the prefix is 0 and seen[0] = 1, so [1, -1] counts. At the third the prefix is 0 and seen[0] = 2, so [1, -1, 0] and [0] count. Total 3.

Complexity

O(n) average time, O(n) space.

Code

python
from collections import defaultdict


def subarray_sum(nums, k):
    """Count contiguous subarrays whose sum is exactly k (works with negatives)."""
    seen = defaultdict(int)
    seen[0] = 1                      # the empty prefix
    prefix = count = 0
    for x in nums:
        prefix += x
        count += seen[prefix - k]    # earlier prefixes p with prefix - p == k
        seen[prefix] += 1
    return count


def subarray_sum_brute(nums, k):
    count = 0
    for i in range(len(nums)):
        s = 0
        for j in range(i, len(nums)):
            s += nums[j]
            if s == k:
                count += 1
    return count


if __name__ == "__main__":
    for f in (subarray_sum, subarray_sum_brute):
        assert f([1, 1, 1], 2) == 2
        assert f([1, 2, 3], 3) == 2
        assert f([1, -1, 0], 0) == 3
        assert f([], 0) == 0
        assert f([3, 4, 7, 2, -3, 1, 4, 2], 7) == 4
    print("all tests passed")

Save as a10_subarray_sum_k.py and run python3 a10_subarray_sum_k.py. It prints all tests passed (Python 3.13.5).

Edge cases

k = 0 with zeros in the list (many overlapping answers). Empty list returns 0. All negative values. Large counts: up to n(n + 1)/2 subarrays, which fits Python integers but would need 64-bit counters in other languages.

Pattern

Prefix sums plus a hash map of earlier prefixes ("complement lookup" on prefix sums). The same structure solves longest subarray with sum k (store the first index instead of a count), subarrays divisible by k (store prefix mod k) and equal numbers of 0s and 1s (map 0 to -1).

python
from collections import defaultdict


def subarray_sum(nums, k):
    """Count contiguous subarrays whose sum is exactly k (works with negatives)."""
    seen = defaultdict(int)
    seen[0] = 1                      # the empty prefix
    prefix = count = 0
    for x in nums:
        prefix += x
        count += seen[prefix - k]    # earlier prefixes p with prefix - p == k
        seen[prefix] += 1
    return count


def subarray_sum_brute(nums, k):
    count = 0
    for i in range(len(nums)):
        s = 0
        for j in range(i, len(nums)):
            s += nums[j]
            if s == k:
                count += 1
    return count


if __name__ == "__main__":
    for f in (subarray_sum, subarray_sum_brute):
        assert f([1, 1, 1], 2) == 2
        assert f([1, 2, 3], 3) == 2
        assert f([1, -1, 0], 0) == 3
        assert f([], 0) == 0
        assert f([3, 4, 7, 2, -3, 1, 4, 2], 7) == 4
    print("all tests passed")

Prefix-sum counting solution with an O(n^2) brute force checked by the same tests.

Complexity

Time: O(n) average. Space: O(n). The brute force in the file is O(n^2) time and O(1) space.

By level

Fresher: Writes the O(n^2) solution, then explains how storing prefix sums in a dictionary removes the inner loop. Should explain why a sliding window fails with negative numbers.

Mid: Implements the counting map with the correct initialisation and order of updates, and explains why a window fails. Explains why the map starts with {0: 1}.

Senior: Generalises to divisible-by-k, longest subarray and 2D submatrix-sum counting, and discusses overflow and memory for large inputs. Can explain why the same map trick finds the longest subarray with sum k.

Key points

  • Subarray sum = difference of two prefix sums
  • Count earlier prefixes equal to prefix - k
  • Initialise with {0: 1} for subarrays starting at index 0
  • Update the map after counting
  • Sliding window fails with negative numbers

Common mistakes

  • Using a sliding window when negatives are allowed
  • Forgetting the {0: 1} initial entry
  • Updating the map before counting and miscounting when k = 0
  • Returning a boolean instead of a count

Follow-ups

  • How would you find the longest subarray with sum k?
  • How do you count subarrays whose sum is divisible by k?
  • What changes if all numbers are positive?

Tips

  • Say why a window fails before proposing the map
  • Walk through a small example with a zero
  • Explain the initial {0: 1}

Evaluation rubric

  • Correct O(n) counting algorithm
  • Explains why sliding window does not apply
  • Handles k = 0 and zeros
  • Correct complexity