Optimal: pairs of (value, min so far)
Time O(1) per operation Space O(n)Push [val, min(val, currentMin)]. The top pair always carries the minimum of everything below and including it, so popping restores the previous minimum automatically.
push -2, push 0, push -3, getMin, pop, top, getMinstack (value, min)(stack)
Step 1/4push −2: min so far −2.
import java.util.ArrayDeque;
import java.util.Deque;
class MinStack {
private final Deque<int[]> stack = new ArrayDeque<>(); // {value, min so far}
public MinStack() {}
public void push(int val) {
int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
stack.push(new int[]{val, min});
}
public void pop() { stack.pop(); }
public int top() { return stack.peek()[0]; }
public int getMin() { return stack.peek()[1]; }
}Verdict: Every operation is a single stack action.