maybe it's O(1) space? I think O(1) time is quite hard...
I had wrote some other solutions, but they are not as easy to understand as this one use stack (I know it's silly...). I remembered that someone made a circle in the list to solve this problem, I cannot come out with a better one so I just put this stupid solution here