interesting problem. Can you solve it in O(n) time