Search for a command to run...
Try your own input
Change the array and replay the algorithm from step one.
Initialization
The trick is that the minimum only ever depends on the entries beneath you. Storing that minimum alongside each value makes push, pop, top and getMin all O(1) — at the cost of a second number per entry.
Value + Min Pairs
1class MinStack {2 constructor() { this.st = []; }//size: 03 4 push(value) {5 if (this.st.length === 0) {6 this.st.push([value, value]);7 return;8 }9 const mini = Math.min(this.getMin(), value);10 this.st.push([value, mini]);11 }12 13 pop() {14 this.st.pop();15 }16 17 top() {18 return this.st[this.st.length - 1][0];19 }20 21 getMin() {22 return this.st[this.st.length - 1][1];23 }24}