Count of Substrings having Sum equal to their Length | Function to count the number of substrings with sum equal to length ; Stores the count of substrings ; Add character to sum ; Add count of substrings to result ; Increase count of subarrays ; Return count ; Driver Code
function countSubstrings ( s , n ) { var count = 0 , sum = 0 ; var mp = new Map ( ) ; if ( mp . has ( 0 ) ) mp . set ( 0 , mp . get ( 0 ) + 1 ) else mp . set ( 0 , 1 ) ; for ( var i = 0 ; i < n ; ++ i ) { sum += ( s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; if ( mp . has ( sum - ( i + 1 ) ) ) count += mp . get ( sum - ( i + 1 ) ) ; if ( mp . has ( sum - ( i + 1 ) ) ) mp . set ( sum - ( i + 1 ) , mp . get ( sum - ( i + 1 ) ) + 1 ) else mp . set ( sum - ( i + 1 ) , 1 ) } return count ; } var str = " " ; var n = str . length ; document . write ( countSubstrings ( str , n ) ) ;