TRT
Sign in
mediumAdvancedLeetCode#prefix sums#hash map of counts

Subarray sum equals K

Count the subarrays whose sum is exactly k, even with negative numbers, using prefix sums and a hash map.

The Runtime Theory Team1 min read
Taught inPrefix sumsPro — members onlyStore the running total at every position once, and the sum of any range becomes one subtraction. Combined with a hash map, prefix sums count subarrays with a given sum, even with negative numbers.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 1, 1], k = 2

out2

innums = [1, 2, 3], k = 3

out2

innums = [1, -1, 0], k = 0

out3

Return the number of contiguous subarrays whose elements sum to k. The array may contain negative numbers.

Before you code

A sliding window fails with negatives. A subarray ending here sums to k exactly when an earlier prefix sum equals the current one minus k.

Hints

  1. Keep a running sum and a map from prefix sum to how many times it has occurred, starting with {0: 1}.
  2. At each element, add seen[S - k] to the answer, then record S.
  3. O(n) time and space.

Production & complexity notes

When solving Subarray sum equals K on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Prefix sums to reinforce the underlying pattern.

What it practices

Prefix sums with a hash map, from Prefix sums.

Not started

Sign in to save your learning progress.

Sign in to save