Lexicographically largest string possible consisting of at most K consecutive similar characters | Function to find largest string ; Stores the frequency of characters ; Traverse the string ; Stores the resultant string ; Append larger character ; Decrease count in charset ; Increase count ; Check if count reached to charLimit ; Find nearest lower char ; If no character can be appended ; Append nearest lower character ; Reset count for next calculation ; Return new largest string ; Function to return nearest lower character ; Traverse charset from start - 1 ; If no character can be appended ; Driver Code
function newString ( originalLabel , limit ) { let n = originalLabel . length ; let charset = new Array ( 26 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { charset [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { charset [ originalLabel [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } let newString = [ ] ; for ( let i = 25 ; i >= 0 ; i -- ) { let count = 0 ; while ( charset [ i ] > 0 ) { newString . push ( String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ) ; charset [ i ] -- ; count ++ ; if ( charset [ i ] > 0 && count == limit ) { let next = nextAvailableChar ( charset , i ) ; if ( next == null ) return newString . join ( " " ) ; newString . push ( next ) ; count = 0 ; } } } return newString . join ( " " ) ; } function nextAvailableChar ( charset , start ) { for ( let i = start - 1 ; i >= 0 ; i -- ) { if ( charset [ i ] > 0 ) { charset [ i ] -- ; return String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; } } return null ; } let S = " " ; let K = 2 ; document . write ( newString ( S , K ) ) ;