155. Min Stack
Intuition
Complexity
Space Complexity
Time Complexity
Code
class MinStack {
Stack<int[]> stackWithMin; // Stack storing value and current min
int currentMin;
public MinStack() {
stackWithMin = new Stack<>();
currentMin = Integer.MAX_VALUE;
}
// Pushes a value and current min onto the stack
public void push(int value) {
currentMin = Math.min(value, currentMin);
stackWithMin.push(new int[]{value, currentMin});
}
// Pops the top element and updates the current min
public void pop() {
stackWithMin.pop();
currentMin = stackWithMin.isEmpty() ? Integer.MAX_VALUE : stackWithMin.peek()[1];
}
// Returns the top value of the stack
public int top() {
return stackWithMin.peek()[0];
}
// Returns the current minimum value in the stack
public int getMin() {
return currentMin;
}
}
Last updated