Find the last remaining Character in the Binary String according to the given conditions | Python3 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
from collections import deque ; NEW_LINE def remainingDigit ( S , N ) : NEW_LINE INDENT c = [ i for i in S ] NEW_LINE de = [ 0 , 0 ] NEW_LINE count = [ 0 , 0 ] NEW_LINE q = deque ( ) NEW_LINE for i in c : NEW_LINE INDENT x = 0 NEW_LINE if i == '1' : NEW_LINE INDENT x = 1 NEW_LINE DEDENT count [ x ] += 1 NEW_LINE q . append ( x ) NEW_LINE DEDENT while ( count [ 0 ] > 0 and count [ 1 ] > 0 ) : NEW_LINE INDENT t = q . popleft ( ) NEW_LINE if ( de [ t ] > 0 ) : NEW_LINE INDENT de [ t ] -= 1 NEW_LINE count [ t ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT de [ t ^ 1 ] += 1 NEW_LINE q . append ( t ) NEW_LINE DEDENT DEDENT if ( count [ 0 ] > 0 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT return "1" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1010100100000" NEW_LINE N = len ( S ) NEW_LINE print ( remainingDigit ( S , N ) ) NEW_LINE DEDENT