this is O(n^2). can you do this in O(n)?