Design a stack that supports push, pop, top and retrieving the minimum element, all in constant time. Input is a LeetCode-style list of operations.
Store each value together with the minimum of the stack at the moment it was pushed. The top pair always knows the current minimum.
1class MinStack {2s: [number, number][] = [];3push(val: number): void {4const min = this.s.length ? Math.min(val, this.s.at(-1)![1]) : val;5this.s.push([val, min]);6}7pop(): void { this.s.pop(); }8top(): number { return this.s.at(-1)![0]; }9getMin(): number { return this.s.at(-1)![1]; }10}
Empty stack.
Space: play/pause · ←/→: step