works but still too slow at O(n^2)