Problem solved at ~O(n^2)