Queries to answer the number of ones and zero to the left of given index | Function to pre - calculate the left [ ] array ; Iterate in the binary array ; Initialize the number of 1 and 0 ; Increase the count ; Driver code ; Queries ; Solve queries
def preCalculate ( binary , n , left ) : NEW_LINE INDENT count1 , count0 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left [ i ] [ 0 ] = count1 NEW_LINE left [ i ] [ 1 ] = count0 NEW_LINE if ( binary [ i ] ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT DEDENT DEDENT binary = [ 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( binary ) NEW_LINE left = [ [ 0 for i in range ( 2 ) ] for i in range ( n ) ] NEW_LINE preCalculate ( binary , n , left ) NEW_LINE queries = [ 0 , 1 , 2 , 4 ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( left [ queries [ i ] ] [ 0 ] , " ones " , left [ queries [ i ] ] [ 1 ] , " zeros " ) NEW_LINE DEDENT