☰ All problems

Subarray Sum Equals K

A food truck records its net result for each day in nums: a loss is negative and a day with no sales is 0. The owner wants to know in how many periods of consecutive days the truck earned exactly k in total.

Count the non-empty contiguous subarrays of nums whose sum equals k. Two periods that start or end on different days are counted separately, even when they overlap.

Example 1
Input: nums = [4,-1,1,4], k = 4
Output: 4

Explanation: The periods are [4] on day 0, [4,-1,1], [-1,1,4] and [4] on day 3.

Example 2
Input: nums = [5,-5,5], k = 5
Output: 3

Explanation: Day 0 alone, day 2 alone, and all three days together.

Example 3
Input: nums = [2,6,-1,-4], k = 10
Output: 0

Explanation: No period adds up to 10.

Constraints

  • nums has between 1 and 20,000 entries.
  • Each daily result is an integer from -1000 to 1000.
  • k is between -10^7 and 10^7.
💡 Hint 1

Negative numbers break the usual sliding-window trick: growing a window does not always increase its sum.

💡 Hint 2

Let prefix[j] be the sum of the first j elements. The subarray from i to j - 1 sums to k exactly when prefix[j] - prefix[i] == k.

💡 Hint 3

Scan once, keeping a hash map from each prefix sum to how many times it has occurred. At each step, add the number of earlier prefixes equal to current - k.

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

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc