Lexicographically smallest string with period K possible by replacing ' ? ' s from a given string | Function to modify the given string such that string S is a period of K ; Iterate over the range [ 0 , K ] ; Stores the frequency of the characters S [ i + j * K ] ; Iterate over the string with increment of K ; Print " - 1" ; Replace all characters of the string with ' ? ' to ' a ' to make it smallest ; Otherwise ; Find the character other than ' ? ' ; Replace all characters of the string with ' ? ' to character ch ; Clear the map M ; Return the modified string ; Driver Code
function modifyString ( S , K ) { let N = S . length ; for ( let i = 0 ; i < K ; i ++ ) { let M = new Map ( ) ; for ( let j = i ; j < N ; j += K ) { if ( M . has ( S [ j ] ) ) { M . set ( M . get ( S [ j ] ) , M . get ( S [ j ] ) + 1 ) ; } else { M . set ( S [ j ] , 1 ) ; } } if ( M . size > 2 ) { return " " ; } else if ( M . size == 1 ) { if ( M . has ( ' ' ) ) { for ( let j = i ; j < N ; j += K ) { S = S . replace ( S [ j ] , ' ' ) ; } } } else if ( M . size == 2 ) { let ch ; for ( let it of M . keys ( ) ) { if ( it != ' ' ) { ch = it ; } } for ( let j = i ; j < N ; j += K ) { S = S . replace ( S [ j ] , ch ) ; } } M . clear ( ) ; } return S ; } let S = " " ; let K = 2 ; document . write ( modifyString ( S , K ) ) ;