Count Subarray sum Equals K
Problem Statement:β
Given an array of integers and an integer k, return the total number of subarrays whose sum equals k.
A subarray is a contiguous non-empty sequence of elements within an array.
-
Example:
Example 1:
Input Format: N = 4, array[] = {3, 1, 2, 4}, k = 6
Result: 2
Explanation: The subarrays that sum up to 6 are [3, 1, 2] and [2, 4].
Example 2:
Input Format: N = 3, array[] = {1,2,3}, k = 3
Result: 2
Explanation: The subarrays that sum up to 3 are [1, 2], and [3].
β Solution: Prefix Sum + HashMapβ
int subarraySum(vector<int>& nums, int k) {
map<long long, int> prefixSumFreq; // stores prefix sum β frequency
long long sum = 0;
int count = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i]; // cumulative sum up to index i
if (sum == k) count++; // case when subarray starts from index 0
long long remaining = sum - k;
if (prefixSumFreq.find(remaining) != prefixSumFreq.end()) {
count += prefixSumFreq[remaining]; // subarrays ending at i with sum = k
}
prefixSumFreq[sum]++; // record the current prefix sum
}
return count;
}
π How It Worksβ
- We use a prefix sum approach:
sum[i] = sum of nums[0..i]. - If
sum[i] - sum[j] == k, then the subarraynums[j+1..i]has sumk. - So, for each running prefix sum
sum, we check ifsum - kwas previously seen. - We use a map (
prefixSumFreq) to store the number of times each prefix sum occurred.
π§© Key Formula / Recurrenceβ
-
Condition:
prefix_sum[i] - prefix_sum[j] == kβ
prefix_sum[j] == prefix_sum[i] - k
β±οΈ Time & Space Complexityβ
| Metric | Complexity |
|---|---|
| Time | O(N) |
| Space | O(N) (map) |
- We iterate once through the array β linear time.
- At most
Ndistinct prefix sums stored in the map.
β οΈ Edge Casesβ
- Elements can be negative (why prefix sum is preferred over sliding window).
- Subarrays can start from index
0(checksum == kdirectly). - Multiple subarrays with the same sum.
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute Force (2 loops) | O(NΒ²) | O(1) | TLE for large inputs |
| Sliding Window | β | β | Doesnβt work with negatives |
| Prefix Sum + Map | β O(N) | O(N) | Best approach |
π Related Problemsβ
- LC 560. Subarray Sum Equals K
- LC 974. Subarray Sums Divisible by K
- LC 525. Contiguous Array
- LC 930. Binary Subarrays With Sum
π οΈ Other Notesβ
-
Think of the prefix sum as a bank account balance:
If your balance now is
sumand you earlier hadsum - k, then you spent exactlykin between β that's your subarray! -
Works for both positive and negative integers.
-
This is a classic "prefix sum + hashmap" pattern for subarray problems.
π¬