Number of subarrays having sum exactly equal to k | Function to find number of subarrays with sum exactly equal to k . ; HashMap 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
function findSubarraySum ( arr , n , sum ) { let prevSum = new Map ( ) ; let res = 0 ; let currsum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == sum ) res ++ ; if ( prevSum . has ( currsum - sum ) ) res += prevSum . get ( currsum - sum ) ; let count = prevSum . get ( currsum ) ; if ( count == null ) prevSum . set ( currsum , 1 ) ; else prevSum . set ( currsum , count + 1 ) ; } return res ; } let arr = [ 10 , 2 , - 2 , - 20 , 10 ] ; let sum = - 10 ; let n = arr . length ; document . write ( findSubarraySum ( arr , n , sum ) ) ;