Replace O(N^2) algorithm with a faster one.