optimize to O(n^2) without coding