Problem
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- getMin() – Retrieve the minimum element in the stack.
Example:
1 | |
Explanation 1
-
Creat two stack
s1ands2.s1is used to like a normal stack to store the elements.s2is used to stroing theminelement. -
In
s2, if the pushing element is smaller or equal than thes2’s top element, that means we have a new min element, so we push this element tos2too. Else, if the pushing element is greater thans2’s top element, we don’t push that intos2, since it doesn’t change theminif we pop it in the future.
Solution 1
1 | |
Explanation 2
-
We can also use only stack to solve this problem, but now, we also need a variable or pointer called
minthat equals to the minimum element. Initialilly,minset to the largest integer. -
When we push an element, we compare
minand the element that get pushx. Ifxis smaller or equal tomin, then we first push theminthen update themin, then pushx. We first push theminbecause thatminrepresents the previousmin. When we later pop element, we don’t want themingoes entirely away, we wantminto update to the previousmin. Else if the element we are pushing is greater thanmin, then we just normally pushxto the stack.
Solution 2
1 | |