Problem · Array
Count Subarrays With Target Sum
Learn this problemProblem statement
Given an integer array nums and an integer target, return the number of non-empty contiguous subarrays whose elements sum exactly to target.
A subarray is a contiguous range of one or more elements. Different index ranges count separately, even when they contain the same values.
Function
countSubarraysWithTargetSum(nums: int[], target: long) → longExamples
Example 1
nums = [1,1,1]target = 2return = 2The subarrays at indices 0 through 1 and 1 through 2 each sum to 2.
Example 2
nums = [1,-1,0]target = 0return = 3The ranges [1, -1], [1, -1, 0], and [0] have sum 0.
Constraints
1 <= nums.length <= 100000-10^9 <= nums[i] <= 10^9-10^14 <= target <= 10^14- The answer fits in a signed 64-bit integer.