Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1 s is always greater than 0 s from left | Function to find lexicographically smallest string having number of 1 s greater than number of 0 s ; C1s And C0s stores the count of 1 s and 0 s at every position ; Traverse the string S ; If the position is not divisible by k1 and k2 ; If C0s >= C1s and pos [ ] is empty then the string can 't  be formed ; If pos [ ] is not empty then flip the bit of last position present in pos [ ] ; Print the result ; Driver Code
function generateString ( k1 , k2 , s ) { let C1s = 0 , C0s = 0 ; let flag = 0 ; let pos = [ ] ; for ( let i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == ' ' ) { C0s ++ ; if ( ( i + 1 ) % k1 != 0 && ( i + 1 ) % k2 != 0 ) { pos . push ( i ) ; } } else { C1s ++ ; } if ( C0s >= C1s ) { if ( pos . length == 0 ) { cout << - 1 ; flag = 1 ; break ; } else { let k = pos [ pos . length - 1 ] ; var ns = s . replace ( s [ k ] , ' ' ) ; C0s -- ; C1s ++ ; pos . pop ( ) ; } } } if ( flag == 0 ) { document . write ( ns ) ; } } let K1 = 2 , K2 = 4 ; let S = " " ; generateString ( K1 , K2 , S ) ;