Problem · Array
Count Subarrays with a 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 to target.
The array may be empty and may contain positive, zero, and negative values. Return 0 when no qualifying subarray exists.
Function
subarraySum(nums: int[], target: int) → intExamples
Example 1
nums = [1,1,1]target = 2return = 2The subarrays at indices [0,1] and [1,2] both sum to 2.
Example 2
nums = [1,-1,0]target = 0return = 3The qualifying subarrays are [1,-1], [0], and [1,-1,0].
Example 3
nums = []target = 5return = 0An empty array has no non-empty subarrays.
Constraints
- Every element and
targetfit in a signed32-bit integer. - Prefix sums are accumulated with a signed
64-bit integer. - The returned count fits in a signed
32-bit integer.