155. Min Stack
Problem description:
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
2
3
4
5
6
7
8MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
Solution:
This problem is a little different from original stack, because it combines features of minheap
and stack
.
We can maintain two stacks. One is to store every element push into the MinStack
, the other only stores the minimum
element.
In the push
function, whenever we need to push an element, check if it’s smaller than the top
element in minstk
.
In pop
function, since every element are definitely in the total
. We can check if the going-to-be-pop-out element from total
is the same as the top
element in minstk
.
1 | class MinStack: |
1 | class MinStack { |
time complexity: $O(1)$
space complexity: $O(n)$
reference: