Improve the running time to O(N * N)