- A stack typically follows a Last In, First Out (LIFO) principle. In addition to the regular stack operations (push, pop, top), the Min Stack must be able to quickly retrieve the minimum element present in the stack at any given time.
- If the value to be pushed is less than or equal to the current minimum:
- push the current
mininto stack. This saves the previousmin - Assign new minimum value to
minvariable.
- push the current
- Push the new value to the stack
- Pop the top value from the stack
- If the popped value equals the current
min, it means the currentminwill be removed from stack. To restore the previousmin:- Pop twice and change the current
minto the last minimumminin the stack
- Pop twice and change the current
- Return the top value of the stack
- Return the current minimum value stored in
min
-
Time complexity: O(1)
-
Space complexity: O(1)
public class MinStack {
private Stack<Integer> stack;
private Integer min;
public MinStack() {
stack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int val) {
if (val <= min) {
stack.push(min);
min = val;
}
stack.push(val);
}
public void pop() {
if (stack.pop().equals(min)) {
min = stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}