Calculate Sum of ratio of special characters to length of substrings of the given string | Javascript program to implement the above approach ; Stores frequency of special characters in the array ; Stores prefix sum ; Function to check whether a character is special or not ; If current character is special ; Otherwise ; Function to find sum of ratio of count of special characters and length of substrings ; Calculate the prefix sum of special nodes ; Generate prefix sum array ; Calculate ratio for substring ; Driver Code ;
var N = 1000005 ; var prefix = Array ( N ) . fill ( 0 ) ; var sum = Array ( N ) . fill ( 0 ) ; function isSpecial ( c , special ) { var ans = false ; special . forEach ( i => { if ( i == c ) ans = true ; } ) ; return ans ; } function countRatio ( s , special ) { var n = s . length ; for ( var i = 0 ; i < n ; i ++ ) { prefix [ i ] = ( isSpecial ( s [ i ] , special ) ) ; if ( i > 0 ) prefix [ i ] += prefix [ i - 1 ] ; } for ( var i = 0 ; i < n ; i ++ ) { sum [ i ] = prefix [ i ] ; if ( i > 0 ) sum [ i ] += sum [ i - 1 ] ; } var ans = 0 ; for ( var i = 1 ; i <= n ; i ++ ) { var count = sum [ n - 1 ] - ( ( i > 1 ) ? sum [ i - 2 ] : 0 ) ; count -= ( ( i < n ) ? sum [ n - i - 1 ] : 0 ) ; ans += ( ( count ) / ( i ) ) ; } return ans ; } var s = " " ; var special = [ ' ' , ' ' ] ; var ans = countRatio ( s . split ( ' ' ) , special ) ; document . write ( ans . toFixed ( 6 ) ) ;