Subarray Sum Equals K

Medium· prefix sum + hash map

Problem

Count the contiguous non-empty subarrays whose elements add up to exactly k. Values may be negative, so a simple sliding window does not work.

Examples

Input: nums = [1,1,1], k = 2
Output: 2
The subarrays at indices 0-1 and 1-2 both sum to 2.
Input: nums = [3,4,-7,2,5], k = 7
Output: 3
[3,4], [2,5] and the whole array [3,4,-7,2,5] each sum to 7.

Constraints

  • • 1 <= nums.length <= 2 * 10^4
  • • -1000 <= nums[i] <= 1000
  • • -10^7 <= k <= 10^7

Hints & approach

Hint 1

A subarray sum is the difference of two prefix sums.

Hint 2

For the current prefix sum P, how many earlier prefix sums equal P - k?

Hint 3

Keep a hash map counting prefix sums seen so far, starting with {0: 1}.

Approachtry the hints first

Walk the array keeping a running prefix sum P and a hash map counting how many times each prefix sum has occurred, seeded with {0: 1} for the empty prefix. At each element, every earlier prefix equal to P - k marks the start of a subarray ending here with sum k, so add count[P - k] to the answer. Then increment count[P]. This handles negative numbers because it never relies on monotonic sums.

Time O(n) · Space O(n)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.