Tricky Solution in O(n) time