Initialize array for Prefix sum
var pre = Array ( N ) . fill ( 0 ) ; pre [ 0 ] = check ( arr [ 0 ] ) ; for ( var i = 1 ; i < N ; i ++ ) { pre [ i ] = pre [ i - 1 ] + check ( arr [ i ] ) ; } var c = 0 ; while ( Q -- ) { var l = queries [ 0 ] ; var r = queries [ 1 ] ; c ++ ; document . write ( query ( l , r , pre ) + ' ' ) ; } }