[Geeks for Geeks] Subarrays with given sum

Subarrays with given sum

Given an unsorted array arr[] of N integers and a sum. The task is to count the number of subarrays which add to a given number.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int subArraySum(int arr[], int n, int sum) {
unordered_map<int, int> mp{{0,1}};
int res = 0;
for(int i = 0, s = 0; i < n; i++) {
s += arr[i];
int target = s - sum;
res += mp[target];
mp[s]++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/subarray-range-with-given-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.