Overview
Design a stack that supports push, pop, top, and getMin — all in O(1) time.
Constraints
-2^31 <= val <= 2^31 - 1pop,top, andgetMinare always called on non-empty stacks.
Examples
const s = new MinStack(); s.push(-2); s.push(0); s.push(-3); s.getMin(); // => -3 s.pop(); s.top(); // => 0 s.getMin(); // => -2
Solution
Reveal solution
class MinStack {
constructor() { this.stack = []; this.minStack = []; }
push(val) { this.stack.push(val); this.minStack.push(Math.min(val, this.minStack.length ? this.minStack[this.minStack.length-1] : val)); }
pop() { this.stack.pop(); this.minStack.pop(); }
top() { return this.stack[this.stack.length - 1]; }
getMin() { return this.minStack[this.minStack.length - 1]; }
}Resources
min-stack.js
Min Stack
mediumcodingAlgorithmsStacks
Overview
Design a stack that supports push, pop, top, and getMin — all in O(1) time.
Constraints
-2^31 <= val <= 2^31 - 1pop,top, andgetMinare always called on non-empty stacks.
Examples
const s = new MinStack(); s.push(-2); s.push(0); s.push(-3); s.getMin(); // => -3 s.pop(); s.top(); // => 0 s.getMin(); // => -2
Solution
Reveal solution
class MinStack {
constructor() { this.stack = []; this.minStack = []; }
push(val) { this.stack.push(val); this.minStack.push(Math.min(val, this.minStack.length ? this.minStack[this.minStack.length-1] : val)); }
pop() { this.stack.pop(); this.minStack.pop(); }
top() { return this.stack[this.stack.length - 1]; }
getMin() { return this.minStack[this.minStack.length - 1]; }
}Resources
NameTopicDifficulty
103 of 103 problems