Design a stack that supports
Implement the
-
MinStack() initializes the stack object. -
void push(int val) pushes the elementval onto the stack. -
void pop() removes the element on the top of the stack. -
int top() gets the top element of the stack. -
int getMin() retrieves the minimum element in the stack.
You must implement a solution with
[[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]
Explanation:
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
Constraints:
-231 <= val <= 231 -1 - Methods
pop ,top andgetMin operations will always be called on non-empty stacks. - At most
3 * 104 calls will be made topush ,pop ,top , andgetMin
Contents
Solution 1 - Implementation of Min Stack using two stacks
In this approach, we are going to implement a min stack using two stacks, in one stack we wil maintain the stack elements that supports standard operations such as
Complexity Analysis:
Time complexity: All the above operations runs in O(1) time.
Space complexity: O(n) for storing stack elements as well as the second stack that we are using to maintain running minimum.
Above implementations source code can be found at