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
function preCalculate ( binary , n , left ) { let count1 = 0 , count0 = 0 ; for ( let i = 0 ; i < n ; i ++ ) { left [ i ] [ 0 ] = count1 ; left [ i ] [ 1 ] = count0 ; if ( binary [ i ] != 0 ) count1 ++ ; else count0 ++ ; } } let binary = [ 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 ] ; let n = binary . length ; let left = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) left [ i ] = [ 0 , 0 ] ; preCalculate ( binary , n , left ) ; let queries = [ 0 , 1 , 2 , 4 ] ; let q = queries . length ; for ( let i = 0 ; i < q ; i ++ ) document . write ( left [ queries [ i ] ] [ 0 ] + " " + left [ queries [ i ] ] [ 1 ] + " " ) ;