Prefixes with more a than b | Function to count prefixes ; calculating for string S ; count == 0 or when N == 1 ; when all characters are a or a - b == 0 ; checking for saturation of string after repetitive addition ; Driver Code
function prefix ( k , n ) { let a = 0 , b = 0 , count = 0 ; let i = 0 ; let len = k . length ; for ( i = 0 ; i < len ; i ++ ) { if ( k [ i ] == ' ' ) a ++ ; if ( k [ i ] == ' ' ) b ++ ; if ( a > b ) { count ++ ; } } if ( count == 0 n == 1 ) { document . write ( count + " " ) ; return 0 ; } if ( count == len a - b == 0 ) { document . write ( ( count * n ) + " " ) ; return 0 ; } let n2 = n - 1 , count2 = 0 ; while ( n2 != 0 ) { for ( i = 0 ; i < len ; i ++ ) { if ( k [ i ] == ' ' ) a ++ ; if ( k [ i ] == ' ' ) b ++ ; if ( a > b ) { count2 ++ ; } } count += count2 ; n2 -- ; if ( count2 == 0 ) break ; if ( count2 == len ) { count += ( n2 * count2 ) ; break ; } count2 = 0 ; } return count ; } let S = " " ; let N = 2 ; document . write ( prefix ( S , N ) + " " ) ; S = " " ; N = 3 ; document . write ( prefix ( S , N ) + " " ) ;