Check if two binary strings can be made equal by swapping 1 s occurring before 0 s | Java program for the above approach ; Function to check if it is possible to make two binary strings equal by given operations ; Stores count of 1 ' s ▁ and ▁ 0' s of the string str1 ; Stores count of 1 ' s ▁ and ▁ 0' s of the string str2 ; Stores current count of 1 's  presenty in the string str1 ; Count the number of 1 ' s ▁ and ▁ 0' s present in the strings str1 and str2 ; If the number of 1 ' s ▁ and ▁ 0' s are not same of the strings str1 and str2 then print not possible ; Traversing through the strings str1 and str2 ; If the str1 character not equals to str2 character ; Swaps 0 with 1 of the string str1 ; Breaks the loop as the count of 1 's is zero. Hence, no swaps  possible ; Swaps 1 with 0 in the string str1 ; Print not possible ; Driver Code ; Given Strings ; Function Call
import java . io . * ; class GFG { static void isBinaryStringsEqual ( String str1 , String str2 ) { int str1Zeros = 0 , str1Ones = 0 ; int str2Zeros = 0 , str2Ones = 0 ; int flag = 0 ; int curStr1Ones = 0 ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( str1 . charAt ( i ) == '1' ) { str1Ones ++ ; } else if ( str1 . charAt ( i ) == '0' ) { str1Zeros ++ ; } if ( str2 . charAt ( i ) == '1' ) { str2Ones ++ ; } else if ( str2 . charAt ( i ) == '0' ) { str2Zeros ++ ; } } if ( str1Zeros != str2Zeros && str1Ones != str2Ones ) { System . out . println ( " Not ▁ Possible " ) ; } else { for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( str1 . charAt ( i ) != str2 . charAt ( i ) ) { if ( str1 . charAt ( i ) == '0' && curStr1Ones > 0 ) { str1 = str1 . substring ( 0 , i ) + '1' + str1 . substring ( i + 1 ) ; curStr1Ones -- ; } if ( str1 . charAt ( i ) == '0' && curStr1Ones == 0 ) { flag ++ ; break ; } if ( str1 . charAt ( i ) == '1' && str2 . charAt ( i ) == '0' ) { str1 = str1 . substring ( 0 , i ) + '0' + str1 . substring ( i + 1 ) ; curStr1Ones ++ ; } } } if ( flag == 0 ) { System . out . println ( " Possible " ) ; } else { System . out . println ( " Not ▁ Possible " ) ; } } } public static void main ( String [ ] args ) { String str1 = "0110" ; String str2 = "0011" ; isBinaryStringsEqual ( str1 , str2 ) ; } }