Introduction
The Subarray Sum Equals K problem involves finding the total number of contiguous subarrays whose sum is equal to a given value k.
Given an array arr[] of size n and an integer k, the task is to count all subarrays having sum exactly equal to k.
This is one of the most important Prefix Sum + HashMap problems and helps in understanding subarray processing, cumulative sums, and efficient lookup techniques.
Example
Input: arr[] = [1, 2, 1, 2, 1]k = 3
Output: 4
Explanation:
Subarrays with sum 3 are:
[1, 2]
[2, 1]
[1, 2]
[2, 1]
Total Count = 4
Input: arr[] = [3, 1, -1, 2, 4]
k = 5
Output: 2
Explanation:
Subarrays with sum 5 are:
[3, 1, -1, 2]
[1, -1, 2, 4]
Total Count = 2
Constraints
1 <= n <= 10^5 -10^9 <= arr[i] <= 10^9 -10^9 <= k <= 10^9
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate all possible subarrays
- Calculate the sum of every subarray
- Count subarrays whose sum equals k.
This approach is easy to understand but repeatedly calculating sums increases time complexity.
Steps
- Traverse all starting indices.
- For every starting index:
- generate subarrays
- Calculate current subarray sum.
- If sum equals k:
- increment count
- Return final count.
Dry Run
Input Array: [1, 2, 1, 2, 1]k = 3
Subarray [1]:
Sum = 1
Subarray [1, 2]:
Sum = 3
Valid Subarray
Count = 1
Subarray [2, 1]:
Sum = 3
Count = 2
Subarray [1, 2]:
Sum = 3
Count = 3
Subarray [2, 1]:
Sum = 3
Count = 4
Final Result:
4
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
All possible subarrays are generated and checked.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Prefix Sum + HashMap)
Explanation
Instead of generating all subarrays, we can use:
- Prefix Sum
- HashMap
The idea is:
If:
currentPrefixSum - previousPrefixSum = kThen:
previousPrefixSum = currentPrefixSum - kSo:
- then a valid subarray exists.
The HashMap stores:
- prefix sum → frequency
This allows subarrays to be counted efficiently.
Steps
- Initialize:
- prefixSum = 0
- count = 0
- hashmap with {0 : 1}
- Traverse the array.
- Add current element to prefix sum.
- Check if:
- (prefixSum - k) exists
- Add its frequency to count.
- Store/update current prefix sum frequency.
Input Array: [1, 2, 1, 2, 1]k = 3
Initially:
prefixSum = 0
count = 0
HashMap:
{0:1}
Traverse 1:
prefixSum = 1
1 - 3 = -2
Not found
Store:
{0:1, 1:1}
Traverse 2:
prefixSum = 3 3 - 3 = 0
Found in map
Count = 1
Store:
{0:1, 1:1, 3:1}
Traverse 1:
prefixSum = 4
4 - 3 = 1
Found in map
Count = 2
Continue similarly...
Final Result:
4
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each element is processed once using HashMap lookups.
Space Complexity: O(n)
Explanation: HashMap stores prefix sum frequencies.
Edge Cases
- Array contains negative numbers
- Multiple overlapping subarrays
- No valid subarray exists
- Array contains zeros
- Entire array sum equals k
Why This Problem is Important
This problem helps in understanding:
- Prefix Sum Technique
- HashMap optimization
- Subarray processing
- Efficient counting techniques
- Cumulative computations
It is one of the most important Prefix Sum interview problems.
Real-World Applications
Prefix Sum and hashing concepts are used in:
- Financial analytics
- Streaming systems
- Time-series processing
- Data aggregation
- Pattern detection systems
Common Mistakes
- Forgetting hashmap initialization {0:1}
- Incorrect prefix sum updates
- Using sliding window for negative numbers
- Overwriting frequencies incorrectly
Interview Tips
Interviewers often expect:
- Prefix Sum optimization
- HashMap usage
- O(n) solution
Always explain why storing prefix sum frequencies helps count valid subarrays efficiently.
Related Questions
- Running Sum
- Longest Subarray with Sum K
- Count Prefix Sum
- Range Sum Query
- Maximum Size Subarray Sum Equals K
Final Takeaway
The Subarray Sum Equals K problem is a fundamental Prefix Sum and HashMap problem that teaches efficient subarray counting and cumulative computation techniques. Understanding this problem builds a strong foundation for advanced hashing, prefix sum, and range query interview problems.