17. Subarray Sum Equals K
Medium · Array
Given an array of integers and a target sum k, count how many contiguous subarrays have a sum equal to k. A subarray must contain at least one element and consist of consecutive elements from the original array. For example, in [1,1,1] with k=2, the subarrays [1,1] at indices 0–1 and [1,1] at indices 1–2 both sum to 2, giving a count of 2.
Input: an array [nums, k] where nums is a list of integers and k is the target sum.
Return: the total count of contiguous subarrays whose sum equals k.
Examples
Example 1 Input: [[1,1,1], 2] Output: 2 Explanation: Two subarrays of length 2 sum to 2
Example 2 Input: [[1,2,3], 3] Output: 2 Explanation: [1,2] and [3]
Constraints
- Standard input/output constraints apply