O(N) solution to this problem