Count how many contiguous subarrays sum to a given value k.
Given an integer array nums and an integer k, count the number of contiguous subarrays whose elements add up exactly to k.
A subarray must consist of consecutive elements from the array, and different starting/ending positions count as different subarrays even if they contain the same values.
Your task is to return the total count of such subarrays.
nums: an integer arrayk: an integer target sumYou may assume the input is well-formed and non-empty unless otherwise stated by the platform version of the problem.
Return an integer representing the number of contiguous subarrays whose sum equals k.
Example 1
Input
nums = [1, 1, 1], k = 2
Output
2
Explanation
The valid subarrays are [1, 1] starting at index 0 and [1, 1] starting at index 1.
Example 2
Input
nums = [1, 2, 3], k = 3
Output
2
Explanation
The valid subarrays are [1, 2] and [3].
Example 3
Input
nums = [1, -1, 0], k = 0
Output
3
Explanation
The valid subarrays are [1, -1], [0], and [1, -1, 0].
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.