Number of subarrays having sum exactly equal to k | C ++ program to find number of subarrays with sum exactly equal to k . ; Function to find number of subarrays with sum exactly equal to k . ; STL map to store number of subarrays starting from index zero having particular value of sum . ; Sum of elements so far . ; Add current element to sum so far . ; If currsum is equal to desired sum , then a new subarray is found . So increase count of subarrays . ; currsum exceeds given sum by currsum - sum . Find number of subarrays having this sum and exclude those subarrays from currsum by increasing count by same amount . ; Add currsum value to count of different values of sum . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubarraySum ( int arr [ ] , int n , int sum ) { unordered_map < int , int > prevSum ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == sum ) res ++ ; if ( prevSum . find ( currsum - sum ) != prevSum . end ( ) ) res += ( prevSum [ currsum - sum ] ) ; prevSum [ currsum ] ++ ; } return res ; } int main ( ) { int arr [ ] = { 10 , 2 , -2 , -20 , 10 } ; int sum = -10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubarraySum ( arr , n , sum ) ; return 0 ; }