Problem · Array
Count Subarrays with Sum K
Learn this problemProblem statement
Given an integer array numbers and an integer target, return the number of non-empty contiguous subarrays whose elements sum to target.
Subarrays with the same values at different positions count separately.
Function
countSubarraysWithSum(numbers: int[], target: int) → intExamples
Example 1
numbers = [1,1,1]target = 2return = 2The qualifying subarrays occupy indices [0,1] and [1,2].
Example 2
numbers = [1,-1,0]target = 0return = 3The qualifying subarrays are [1,-1], [1,-1,0], and [0].
Constraints
1 <= numbers.length <= 100000-10000 <= numbers[i] <= 10000-10^9 <= target <= 10^9- The answer fits in a signed 32-bit integer.