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
s1
ands2
.s1
is used to like a normal stack to store the elements.s2
is used to stroing themin
element. -
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 tos2
too. Else, if the pushing element is greater thans2
’s top element, we don’t push that intos2
, since it doesn’t change themin
if 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
min
that equals to the minimum element. Initialilly,min
set to the largest integer. -
When we push an element, we compare
min
and the element that get pushx
. Ifx
is smaller or equal tomin
, then we first push themin
then update themin
, then pushx
. We first push themin
because thatmin
represents the previousmin
. When we later pop element, we don’t want themin
goes entirely away, we wantmin
to update to the previousmin
. Else if the element we are pushing is greater thanmin
, then we just normally pushx
to the stack.
Solution 2
1 |
|