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 | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; void generateString ( int k1 , int k2 , string s ) { int C1s = 0 , C0s = 0 ; int flag = 0 ; vector < int > pos ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '0' ) { C0s ++ ; if ( ( i + 1 ) % k1 != 0 && ( i + 1 ) % k2 != 0 ) { pos . push_back ( i ) ; } } else { C1s ++ ; } if ( C0s >= C1s ) { if ( pos . size ( ) == 0 ) { cout << -1 ; flag = 1 ; break ; } else { int k = pos . back ( ) ; s [ k ] = '1' ; C0s -- ; C1s ++ ; pos . pop_back ( ) ; } } } if ( flag == 0 ) { cout << s ; } } int main ( ) { int K1 = 2 , K2 = 4 ; string S = "11000100" ; generateString ( K1 , K2 , S ) ; return 0 ; }