Count Subarrays with Sum K
Problem statement
You are given an integer array arr and an integer k.
A subarray is a non-empty run of consecutive elements of arr. Return how many subarrays have elements that add up to exactly k.
Subarrays at different positions count separately, even when they hold the same values.
Function
countSubarrays(arr: int[], k: int) → intExamples
Example 1
arr = [2,-1,1,2]k = 2return = 4Four subarrays add up to 2: [2] at the start, [2,-1,1], [-1,1,2], and [2] at the end. The answer is 4.
Example 2
arr = [0,0,0]k = 0return = 6Every one of the six subarrays sums to 0: three of length 1, two of length 2, and one of length 3. The answer is 6.
Example 3
arr = [4,1,2]k = 6return = 0The sums are 4, 5, 7 starting at index 0, 1, 3 starting at index 1, and 2 starting at index 2. None is 6, so the answer is 0.
Constraints
1 <= arr.length <= 2 * 10^4-10^4 <= arr[i] <= 10^4-2 * 10^8 <= k <= 2 * 10^8