Stack · Medium
Min Stack: the idea to remember.
Support push, pop, top and minimum queries in constant time on a nonempty query stack.
The core insight
Store each pushed value together with the minimum at that depth.
Why it works
The top pair remembers the minimum of exactly the surviving stack prefix, even after pops.
The mistake to avoid
A single global minimum cannot recover the previous minimum after a pop.
Time: O(1) per operationSpace: O(n)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
class MinStack {
private final Deque<int[]> stack = new ArrayDeque<>();
public void push(int value) {
int min = stack.isEmpty() ? value : Math.min(value, stack.peek()[1]);
stack.push(new int[]{value, min});
}
public void pop() { stack.pop(); }
public int top() { return stack.peek()[0]; }
public int getMin() { return stack.peek()[1]; }
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.