Make Palindrome binary string with exactly a 0 s and b 1 s by replacing wild card ? | Function to convert the given string to a palindrome with a 0 ' s ▁ and ▁ b ▁ 1' s ; Stores the size of the string ; Loop to iterate over the string ; If one of S [ i ] or S [ N - i - 1 ] is equal to ' ? ' , replace it with corresponding character ; Subtract the count of 0 from the required number of zeroes ; Subtract the count of 1 from required number of ones ; Traverse the string ; If both S [ i ] and S [ N - i - 1 ] are ' ? ' ; If a is greater than b ; Update S [ i ] and S [ N - i - 1 ] to '0' ; Update the value of a ; Update S [ i ] and S [ N - i - 1 ] to '1' ; Update the value of b ; Case with middle character ' ? ' in case of odd length string ; If a is greater than b ; Update middle character with '0' ; Update middle character by '1' ; Return Answer ; Driver Code
const convertString = ( S , a , b ) => { let N = S . length ; for ( let i = 0 ; i < parseInt ( N / 2 ) ; ++ i ) { if ( S [ i ] == ' ' && S [ N - i - 1 ] != ' ' ) { S [ i ] = S [ N - i - 1 ] ; } else if ( S [ i ] != ' ' && S [ N - i - 1 ] == ' ' ) { S [ N - i - 1 ] = S [ i ] ; } } let cnt_0 = 0 ; for ( let i = 0 ; i < N ; ++ i ) { if ( S [ i ] == ' ' ) cnt_0 ++ ; } a = a - cnt_0 ; let cnt_1 = 0 ; for ( let i = 0 ; i < N ; ++ i ) { if ( S [ i ] == ' ' ) cnt_1 ++ ; } b = b - cnt_1 ; for ( let i = 0 ; i < parseInt ( N / 2 ) ; ++ i ) { if ( S [ i ] == ' ' && S [ N - i - 1 ] == ' ' ) { if ( a > b ) { S [ i ] = S [ N - i - 1 ] = ' ' ; a -= 2 ; } else { S [ i ] = S [ N - i - 1 ] = ' ' ; b -= 2 ; } } } if ( S [ parseInt ( N / 2 ) ] == ' ' ) { if ( a > b ) { S [ parseInt ( N / 2 ) ] = ' ' ; a -- ; } else { S [ parseInt ( N / 2 ) ] = ' ' ; b -- ; } } if ( a == 0 && b == 0 ) { return S ; } else { return " " ; } } let S = " " ; S = S . split ( ' ' ) ; let a = 4 , b = 4 ; document . write ( convertString ( S , a , b ) . join ( ' ' ) ) ;