Subarray Sum Equals K

Medium#560subarray sum

You get an array of integers, negative ones included, and a number k. Count the contiguous subarrays whose numbers add up to exactly k. Our example: [1, 2, -1, 3, -2, 2] and k = 3 — the answer is 4: [1, 2], [3], [3, -2, 2] and [1, 2, -1, 3, -2].

input
nums: integers, negative ones included; k: an integer.
returns
How many contiguous subarrays of nums add up to exactly k.
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −1000 ≤ nums[i] ≤ 1000
  • −10⁷ ≤ k ≤ 10⁷
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
function subarraySum(nums, k) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more prefix sums problems

Pattern “Prefix sums” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.