Min Stack Visualizer & Step-by-Step Algorithm Solution

Design a stack supporting push, pop, top, and retrieving the minimum element in constant O(1) time using an auxiliary monotonic min-tracker stack.

Category: stack | Difficulty: Medium

Tags: Stack, Design, Monotonic Stack, Constant Time

Min Stack

Operations Stream
push(1)
0
push(2)
1
push(0)
2
getMin()
3
pop()
4
top()
5
getMin()
6
Return Values
0
1
2
3
4
5
6
Push / Pop (Top)
(Empty Stack)
Main Stack (Values)
Push / Pop (Top)
(Empty Stack)
Min Stack (Track Min)
100%
state
op
stackSize0
minStackSize0
stackTopempty
currentMinnone
totalOperations7
Initialization
1/32
Explanation

Instantiate MinStack to process 7 stream operations with O(1) push, pop, top, and getMin.

Source Code
1class MinStack {
2 private minStack: number[] = [];
3 private stack: number[] = [];
4 push(val: number): void {
5 this.stack.push(val);
6 const currentMin = this.minStack.length === 0
7 ? val
8 : Math.min(val, this.minStack[this.minStack.length - 1]);
9 this.minStack.push(currentMin);
10 }
11 pop(): void {
12 this.stack.pop();
13 this.minStack.pop();
14 }
15 top(): number {
16 return this.stack[this.stack.length - 1];
17 }
18 getMin(): number {
19 return this.minStack[this.minStack.length - 1];
20 }
21}