Define the prefix sum arrays globally
let prefix_sum_row = new Array ( 50 ) ; for ( let i = 0 ; i < prefix_sum_row . length ; i ++ ) { prefix_sum_row [ i ] = new Array ( 51 ) . fill ( 0 ) ; } let prefix_sum_col = new Array ( 50 ) ; for ( let i = 0 ; i < prefix_sum_col . length ; i ++ ) { prefix_sum_col [ i ] = new Array ( 51 ) . fill ( 0 ) ; } function is_valid ( r , c , size , grid ) { let r_end = r + size , c_end = c + size ;