Subarray Sum Equals K
Given an integer array nums and an integer k, return the total number of contiguous subarrays whose elements sum to exactly k.
Open official problem prompt ↗Count how many contiguous slices of the array add up to exactly k, including slices that overlap.
Think of running mileage markers on a road. A stretch of road covers exactly k miles whenever two markers differ by k, so at each marker you ask how many earlier markers sat exactly k miles behind you.
- Input
- nums = [1, 1, 1], k = 2
- Output
- 2
- Why
- The subarrays nums[0..1] and nums[1..2] both sum to 2.
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7