Subarray Sum Equals K
Problem statement
Given an integer array nums and integer k, return how many nonempty contiguous subarrays have sum exactly k. Subarrays with different start or end positions count separately, even when their values are equal.
Values may be negative or zero. An empty input has zero qualifying subarrays.
Function
countSubarrays(nums: int[], k: int) → intExamples
Example 1
nums = [1,1,1]k = 2return = 2The two adjacent length-two subarrays each sum to two.
Example 2
nums = [1,-1,0]k = 0return = 3The qualifying subarrays are [1,-1], [0], and [1,-1,0].
Constraints
0 <= nums.length <= 20000.-10^9 <= nums[i], k <= 10^9.- Use wide arithmetic for running sums; the returned count fits a signed 32-bit integer.