Design a stack that supports push, pop, top, and retrieving the minimum element — all in O(1) time.
push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()[-3, 0, -2]push(5), push(3), push(7), getMin(), pop(), getMin(), push(1), getMin()[3, 3, 1]stack (values) and minSt (running minimums)min(val, minSt.peek()) to minStThe min-stack mirrors the main stack level-for-level. Each entry minSt[i] stores the minimum of the entire main stack at that depth. When an element is popped, its corresponding min entry is also discarded — so minSt.peek() always reflects the current minimum without any scanning.
Scanning the whole stack for the minimum is O(n) per call. Keeping one minimum variable breaks after a pop, because you lose the previous minimum.
Keep a second stack of minimums, the same height as the main stack. Each entry is the minimum of everything at or below that level. Push and pop both stacks together, and the minimum is always on top.
Store the minimum at every level. Then pops can never lose the previous minimum.
Run the animation above on your own input, or watch the 1:20 video explanation of Min Stack with a dry run and Java code.