correct the O(N) solution, it was wrong