Improve the efficiency of the code 

From N^4 to N^2 for intermediate data size