03.02. Min Stack
Description
How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> return -3. minStack.pop(); minStack.top(); --> return 0. minStack.getMin(); --> return -2.
Solutions
Solution 1: Double Stack
We use two stacks to implement this, where stk1
is used to store data, and stk2
is used to store the current minimum value in the stack. Initially, stk2
stores a very large value.
- When we push an element
x
into the stack, we pushx
intostk1
, and pushmin(x, stk2[-1])
intostk2
. - When we pop an element from the stack, we pop the top elements of both
stk1
andstk2
. - When we want to get the top element in the current stack, we just need to return the top element of
stk1
. - When we want to get the minimum value in the current stack, we just need to return the top element of
stk2
.
For each operation, the time complexity is $O(1)$, and the space complexity is $O(n)$.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |