Initialize array for Prefix sum
int [ ] pre = new int [ N ] ; pre [ 0 ] = check ( arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { pre [ i ] = pre [ i - 1 ] + check ( arr [ i ] ) ; } int c = 0 ; int q = 0 ; while ( q < Q ) { int l = queries . get ( q ) . item1 ; int r = queries . get ( q ) . item2 ; c ++ ; q ++ ; System . out . print ( query ( l , r , pre ) + " ▁ " ) ; } }