Find subarray with given sum | Set 2 ( Handles Negative Numbers ) | Function to print subarray with sum as given sum ; cur_sum to keep track of cummulative sum till that polet ; check whether cur_sum - sum = 0 , if 0 it means the sub array is starting from index 0 - so stop ; if hashMap already has the value , means we already have subarray with the sum - so stop ; if value is not present then add to hashmap ; if end is - 1 : means we have reached end without the sum ; Driver program
function subArraySum ( arr , n , sum ) { let cur_sum = 0 ; let start = 0 ; let end = - 1 ; let hashMap = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { cur_sum = cur_sum + arr [ i ] ; if ( cur_sum - sum == 0 ) { start = 0 ; end = i ; break ; } if ( hashMap . has ( cur_sum - sum ) ) { start = hashMap . get ( cur_sum - sum ) + 1 ; end = i ; break ; } hashMap . set ( cur_sum , i ) ; } if ( end == - 1 ) { document . write ( " " ) ; } else { document . write ( " " + start + " " + end ) ; } } let arr = [ 10 , 2 , - 2 , - 20 , 10 ] ; let n = arr . length ; let sum = - 10 ; subArraySum ( arr , n , sum ) ;