Given an integer array nums and an integer k, return the number of contiguous subarrays whose sum is exactly equal to k.
A subarray is a contiguous non-empty sequence of elements within an array.
Function Signature
def count_subarrays_with_sum(nums: list[int], k: int) -> int:
Rules
-
A subarray is a non-empty run of consecutive elements
nums[i..j]
with
i <= j
.
-
Subarrays are counted by position. Two subarrays with the same values at different indices count separately.
-
Elements and
k
may be negative or zero.
Constraints
-
1 <= len(nums) <= 10^5
-
-1000 <= nums[i] <= 1000
-
-10^7 <= k <= 10^7
Examples
Input: nums = [1, 1, 1], k = 2
Output: 2
The subarrays [1, 1] at indices 0-1 and [1, 1] at indices 1-2 both sum to 2. They hold the same values but sit at different positions, so both count.
Input: nums = [1, 2, 3], k = 3
Output: 2
The subarrays [1, 2] and [3] both sum to 3.
Input: nums = [1, -1, 0], k = 0
Output: 3
The subarrays [0], [1, -1] and [1, -1, 0] sum to 0. The other three, [1], [-1] and [-1, 0], sum to 1, -1 and -1.