Subarray Sum Equals K
mediumLeetCode Top 100arrayshashingprefix-sum
Problem
Given a list of integers and a target k, count how many contiguous subarrays sum to exactly k. Values may be negative.
Examples
Input: nums = [1, 1, 1], k = 2
Output: 2
The subarrays [1,1] at positions 0-1 and 1-2 each sum to 2.
Input: nums = [1, 2, 3], k = 3
Output: 2
[3] and [1,2] both sum to 3.
Constraints
- • 1 <= nums.length <= 2 * 10^4
- • -1000 <= nums[i] <= 1000
- • -10^7 <= k <= 10^7
Hints(tap to reveal)
- 1. A subarray sum is a difference of two prefix sums.
- 2. Count prefix sums seen so far in a hash map.
Optimal approach(spoiler)
- Maintain a running prefix sum as you scan.
- Store the frequency of each prefix sum in a hash map, seeded with sum zero once.
- At each step, look up how many earlier prefix sums equal current sum minus k.
- Add that count to the answer, then record the current prefix sum.
- O(n) time, O(n) space; handles negatives that a sliding window cannot.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor