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:
MinStack 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 1 (two stack)
Intuitive solution is to use 2 stacks, one stack to maintain value, and one stack to maintain min value.
For example:
Complexity Analysis
Time Complexity:O(N)
Space Complexity:O(N)
Code
classMinStack {Stack<Integer> stack;Stack<Integer> minStack; /** initialize your data structure here. */publicMinStack() { stack =newStack<>(); minStack =newStack<>(); }publicvoidpush(int x) {stack.push(x);int curr =minStack.isEmpty() ? x :minStack.peek();minStack.push(curr > x ? x : curr); }publicvoidpop() {stack.pop();minStack.pop(); }publicinttop() {returnstack.peek(); }publicintgetMin() {returnminStack.peek(); }}
Solution 2 (one stack)
From solution 1, we observe that we maintain 2 stacks every operation and 1 stack to keep one state, and with that thought, we can use one stack to maintain 2 states, how to maintain 2 states in one action, using helper class.
helper class Node with value and min value, and stack to maintain Node status.