Subarray Sum Equals K

Given an array of integers nums and an integer k, return the number of contiguous, non-empty subarrays whose elements add up to exactly k.

The array may contain negative numbers and zeros. Subarrays at different positions count separately, even if they contain the same values.

Constraints

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

Examples

Example 1

Input: nums = [1,2,1,2,1], k = 3
Output: 4

[1, 2] at indices 0–1, [2, 1] at 1–2, [1, 2] at 2–3 and [2, 1] at 3–4: four subarrays.

Example 2

Input: nums = [3,4,-7,3,1], k = 0
Output: 2

[3, 4, -7] and [4, -7, 3] both sum to 0. Negative numbers are allowed, so a window can't be used.

Example 3

Input: nums = [1], k = 0
Output: 0

The only subarray, [1], sums to 1.

JavaScript you'll use: Map and Set Arrays: create, read, update

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
function subarraySum(nums, k) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.