Subarray Sum Equals K
medium
arrays
hashmap
prefix-sum
Given an integer array nums and an integer k, return the total number of contiguous subarrays whose elements sum to exactly k.
Input / output
- Input:
nums: int[],k: int - Output: the count of qualifying subarrays
Examples
nums = [1, 1, 1],k = 2returns2.nums = [1, 2, 3],k = 3returns2.nums = [1, -1, 0],k = 0returns3.
Constraints
1 <= nums.length <= 20000-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
Edge cases
- Values may be negative or zero, so sliding-window shrinking does not apply.
- Subarrays that start at index
0are counted via an initial prefix sum of0.
Target complexity
- Aim for
O(n)time andO(n)extra space.
Hints
- A subarray sum equals
prefix[j] - prefix[i]; you want that difference to equalk. - While scanning, count how many earlier prefix sums equal
current - k.
Follow-up Why does the negative-number case rule out the classic shrinking sliding-window approach?
Examples
Example 1
Input: nums = [1,1,1], k = 2
Output: 2
Example 2
Input: nums = [1,2,3], k = 3
Output: 2
Example 3
Input: nums = [1,-1,0], k = 0
Output: 3
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.