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
< ? php function preCalculate ( $ binary , $ n ) { $ left = array ( ) ; $ count1 = 0 ; $ count0 = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ left [ $ i ] = array ( $ count1 , $ count0 ) ; if ( $ binary [ $ i ] ) $ count1 ++ ; else $ count0 ++ ; } return $ left ; } $ binary = array ( 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 ) ; $ n = count ( $ binary ) ; $ left = preCalculate ( $ binary , $ n ) ; $ queries = array ( 0 , 1 , 2 , 4 ) ; $ q = count ( $ queries ) ; for ( $ i = 0 ; $ i < $ q ; $ i ++ ) echo $ left [ $ queries [ $ i ] ] [ 0 ] , " ▁ ones ▁ " , $ left [ $ queries [ $ i ] ] [ 1 ] , " ▁ zeros STRNEWLINE " ; ? >