Find the last remaining Character in the Binary String according to the given conditions | Java implementation of the above approach ; Converting string to array ; Delete counters for each to count the deletes ; Counters to keep track of characters left from each type ; Queue to simulate the process ; Initializing the queue ; Looping till at least 1 digit is left from both the type ; If there is a floating delete for current character we will delete it and move forward otherwise we will increase delete counter for opposite digit ; If 0 are left then answer is 0 else answer is 1 ; Driver Code ; Input String ; Length of String ; Printing answer
import java . util . * ; public class GfG { private static String remainingDigit ( String S , int N ) { char c [ ] = S . toCharArray ( ) ; int del [ ] = { 0 , 0 } ; int count [ ] = { 0 , 0 } ; Queue < Integer > q = new LinkedList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int x = c [ i ] == '1' ? 1 : 0 ; count [ x ] ++ ; q . add ( x ) ; } while ( count [ 0 ] > 0 && count [ 1 ] > 0 ) { int t = q . poll ( ) ; if ( del [ t ] > 0 ) { del [ t ] -- ; count [ t ] -- ; } else { del [ t ^ 1 ] ++ ; q . add ( t ) ; } } if ( count [ 0 ] > 0 ) return "0" ; return "1" ; } public static void main ( String args [ ] ) { String S = "1010100100000" ; int N = S . length ( ) ; System . out . print ( remainingDigit ( S , N ) ) ; } }