Subarray Sum Equals K

35 min · subarraySum()

A week of gains and losses can swing in both directions yet still finish exactly on a target. The matching stretch might begin anywhere, and more than one stretch can land on the same total.

Given an integer array nums and an integer k, return how many contiguous subarrays — non-empty slices whose elements sit next to one another — add up to exactly k.

A few ground rules:

  • Count every distinct choice of start and end positions, even when two slices contain the same values.
  • The empty slice doesn't count.
  • Values may be positive, negative, or zero. A running total can cross k and later come back, so "too large" isn't a safe reason to stop.

Constraints

  • 1 <= nums.length <= 100_000
  • -1_000 <= nums[i] <= 1_000
  • -10_000_000 <= k <= 10_000_000
  • The answer fits in a signed 32-bit integer.

Hints

Start from every position

Fix a starting index, grow the slice one value at a time, and keep its sum. That avoids re-adding the whole slice, but how many start/end pairs remain?

Turn a slice into a difference

If the running total through the current position is sum, a slice ending here totals k when an earlier running total was exactly sum - k.

Frequency matters

The same earlier total may occur several times, and each occurrence gives a different slice. Store running total → number of times seen, beginning with 0 → 1 for the position before the array starts.

Follow-up

Could you process the numbers as a stream, counting every new matching slice without storing the original array?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  1,
  1
]
k = 2
Expected
2
Why
the first two and last two values each total 2

Example 2

ready
Input
nums = [
  1,
  2,
  3
]
k = 3
Expected
2
Why
[1, 2] and [3] are two different contiguous slices

Example 3

ready
Input
nums = [
  1,
  -1,
  0
]
k = 0
Expected
3
Why
negative values cancel, and the final zero also counts alone

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite