[LeetCode] Min Stack (Python3)
Thoughts:
The first thing that came to my mind was to maintain a min value. However, if there are multiple min value in the stack, it’s impossible to check whether the min value has changed when popping out a value.
Luckily, the specialty of stacks make sure that you always know what value is popped. Therefore, by maintaining “the current min value” stack allows us to easily trace back previous min values.
When pushing a new value into the stack, check the min value and pop in the new min (whether it’s changed or not) into the second stack as well. Therefore, when you are popping elements, you simply need to pop element from the second stack to restore previous min value. This works because if the min is updated then it must because of the top value in stack, so if you pop the top element then it will go back to before.
1 |
|