text: 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 | Java program for the above approach ; 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
code: import java . util . * ; class GFG { static void generateString ( int k1 , int k2 , char [ ] s ) { int C1s = 0 , C0s = 0 ; int flag = 0 ; Vector < Integer > pos = new Vector < Integer > ( ) ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == '0' ) { C0s ++ ; if ( ( i + 1 ) % k1 != 0 && ( i + 1 ) % k2 != 0 ) { pos . add ( i ) ; } } else { C1s ++ ; } if ( C0s >= C1s ) { if ( pos . size ( ) == 0 ) { System . out . print ( - 1 ) ; flag = 1 ; break ; } else { int k = pos . get ( pos . size ( ) - 1 ) ; s [ k ] = '1' ; C0s -- ; C1s ++ ; pos . remove ( pos . size ( ) - 1 ) ; } } } if ( flag == 0 ) { System . out . print ( s ) ; } } public static void main ( String [ ] args ) { int K1 = 2 , K2 = 4 ; String S = "11000100" ; generateString ( K1 , K2 , S . toCharArray ( ) ) ; } }