30. Subarrays with Sum K
β GFG solution to the Subarrays with Sum K problem: count number of subarrays with exact sum K using prefix sum and hash map technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an unsorted array arr[]
of integers and a target sum k
. Your task is to find the number of subarrays whose sum is exactly equal to the given number k
.
A subarray is a contiguous sequence of elements within an array. The goal is to count all possible subarrays where the sum of elements equals the target value k
.
π Examples
Example 1
Input: arr[] = [10, 2, -2, -20, 10], k = -10
Output: 3
Explanation: Subarrays: arr[0...3], arr[1...4], arr[3...4] have sum exactly equal to -10.
- arr[0...3] = [10, 2, -2, -20] β sum = -10
- arr[1...4] = [2, -2, -20, 10] β sum = -10
- arr[3...4] = [-20, 10] β sum = -10
Example 2
Input: arr[] = [9, 4, 20, 3, 10, 5], k = 33
Output: 2
Explanation: Subarrays: arr[0...2], arr[2...4] have sum exactly equal to 33.
- arr[0...2] = [9, 4, 20] β sum = 33
- arr[2...4] = [20, 3, 10] β sum = 33
Example 3
Input: arr[] = [1, 3, 5], k = 0
Output: 0
Explanation: No subarray with 0 sum exists in the array.
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$-10^3 \le \text{arr}[i] \le 10^3$
$-10^5 \le k \le 10^5$
β
My Approach
The optimal approach uses Prefix Sum technique with a Hash Map to efficiently count subarrays with the target sum:
Prefix Sum + Hash Map
Core Insight:
If prefix sum at index
j
issum
and prefix sum at indexi-1
issum-k
, then subarray fromi
toj
has sumk
.We need to count how many times
(current_prefix_sum - k)
has occurred before.
Algorithm Steps:
Initialize hash map with
{0: 1}
to handle subarrays starting from index 0.Traverse array and maintain running prefix sum.
For each element, check if
(prefix_sum - k)
exists in hash map.Add the frequency of
(prefix_sum - k)
to result count.Update hash map with current prefix sum.
Key Formula:
subarray_sum[i...j] = prefix_sum[j] - prefix_sum[i-1]
If
subarray_sum[i...j] = k
, thenprefix_sum[i-1] = prefix_sum[j] - k
Why This Works:
Hash map stores frequency of each prefix sum encountered.
When we find
prefix_sum - k
in map, it means there are that many subarrays ending at current position with sumk
.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We traverse the array once, and hash map operations (insert/lookup) take O(1) average time.
Expected Auxiliary Space Complexity: O(n), where n is the size of the array. In the worst case, all prefix sums are distinct, requiring O(n) space for the hash map.
π§βπ» Code (C++)
class Solution {
public:
int cntSubarrays(vector<int>& arr, int k) {
unordered_map<int, int> mp;
int sum = 0, cnt = 0;
mp[0] = 1;
for (int x : arr) {
sum += x;
cnt += mp[sum - k];
mp[sum]++;
}
return cnt;
}
};
β Code (Java)
class Solution {
public int cntSubarrays(int[] arr, int k) {
Map<Integer, Integer> map = new HashMap<>();
int sum = 0, count = 0;
map.put(0, 1);
for (int num : arr) {
sum += num;
count += map.getOrDefault(sum - k, 0);
map.merge(sum, 1, Integer::sum);
}
return count;
}
}
π Code (Python)
class Solution:
def cntSubarrays(self, arr, k):
mp, s, cnt = {0: 1}, 0, 0
for x in arr:
s += x
cnt += mp.get(s - k, 0)
mp[s] = mp.get(s, 0) + 1
return cnt
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated