Number of subsequences as " ab " in a string repeated K times | JavaScript code to find number of subsequences of " ab " in the string S which is repeated K times . ; Count of ' a ' s ; Count of ' b ' s ; Occurrence of " ab " s in string S ; Add following two : 1 ) K * ( Occurrences of " ab " in single string ) 2 ) a is from one string and b is from other . ; Driver Code
function countOccurrences ( s , K ) { let n = s . length ; let C = 0 , c1 = 0 , c2 = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) c1 ++ ; if ( s [ i ] == ' ' ) { c2 ++ ; C += c1 ; } } return C * K + ( K * ( K - 1 ) / 2 ) * c1 * c2 ; } let S = " " ; let k = 2 ; document . write ( countOccurrences ( S , k ) ) ;