mediumArrays & HashingPure DSA~25 min
Count Contiguous Spans Summing To Target
A stream of per-minute transaction deltas (which may be negative for refunds) is recorded in order. Count how many contiguous time spans have deltas summing to exactly a target volume k.
Problem
Given an integer array nums and an integer k, return the total number of contiguous subarrays whose elements sum to exactly k. Values may be negative.
Input
An integer array nums and an integer k.
Output
The count of subarrays whose sum equals k.
Constraints
- 1 ≤ n ≤ 2e4
- -1000 ≤ nums[i] ≤ 1000
- -1e7 ≤ k ≤ 1e7
Examples
Example 1
Input
nums=[1,1,1] k=2
Output
2
[1,1] at indices (0,1) and (1,2) each sum to 2.
Example 2
Input
nums=[1,2,3] k=3
Output
2
[3] and [1,2] both sum to 3.