Subarray Sum Equals K
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
numsadd up to exactlyk. - constraints
- 1 ≤ nums.length ≤ 10⁴
- −1000 ≤ nums[i] ≤ 1000
- −10⁷ ≤ k ≤ 10⁷
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more prefix sums problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.