Queries to answer the number of ones and zero to the left of given index | Java implementation of the approach ; pair class ; 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
class GFG { static class pair { int first , second ; pair ( int a , int b ) { first = a ; second = b ; } } static void preCalculate ( int binary [ ] , int n , pair left [ ] ) { int count1 = 0 , count0 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] . first = count1 ; left [ i ] . second = count0 ; if ( binary [ i ] != 0 ) count1 ++ ; else count0 ++ ; } } public static void main ( String args [ ] ) { int binary [ ] = { 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 } ; int n = binary . length ; pair left [ ] = new pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) left [ i ] = new pair ( 0 , 0 ) ; preCalculate ( binary , n , left ) ; int queries [ ] = { 0 , 1 , 2 , 4 } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( left [ queries [ i ] ] . first + " ▁ ones ▁ " + left [ queries [ i ] ] . second + " zerosNEW_LINE"); } }