Subarray Sum Equals K

Medium Prefix Sum AI round

nums is a list of whole numbers, and k is one more whole number. Any of them may be negative or zero.

A subarray is a run of numbers next to each other in nums: one number, or several with none left out between the first and the last. Two subarrays are different when they start or end at different places, even if their numbers are the same.

Return how many subarrays of nums add up to exactly k.

Example 1

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

Five subarrays add up to 2: [2] at the start, [2, -1, 3, -2], [-1, 3], [-1, 3, -2, 2] and [2] at the end.

Example 2

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

Every subarray adds up to 0: three of one number, two of two numbers and the whole list.

Example 3

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

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁵
  • -5000 ≤ nums[i] ≤ 5000
  • -10⁹ ≤ k ≤ 10⁹
  • The answer is less than 2³¹, so it fits in a signed 32-bit integer

Watch the explanation

More Prefix Sum

All Prefix Sum problems