Design a stack that reports its minimum value in constant time.
Use the editor below to process MinStack operations.
Use constant-time stack operations
Track minimum history as values are pushed and popped so getMin takes O(1) time. After removing one copy of a duplicate minimum, another copy must still count as the minimum.
Submit your implementation when it passes the examples.
Process a sequence of MinStack operations. push, pop, top, and getMin must all run in constant time.
Return one output per operation. Constructors, push, and pop produce null; top and getMin produce numbers.
At most 30,000 operations are performed.Results appear here after a run.
For every entry in the value stack, store the minimum at that depth in a second stack. On the first push, the minimum is the value itself. On later pushes, append the smaller of the new value and the previous minimum.
In the diagram, pushing 7 onto [5, 2] records another 2 in the minimum stack. Pushing 1 records 1. A pop removes one entry from each stack, restoring the minimum at the previous depth. The same rule handles duplicate minimum values.
function runMinStack(operations, values) {
class MinStack {
constructor() {
this.items = [];
this.minimums = [];
}
push(value) {
this.items.push(value);
const previous = this.minimums[this.minimums.length - 1];
this.minimums.push(previous === undefined ? value : Math.min(value, previous));
}
pop() {
this.items.pop();
this.minimums.pop();
}
top() {
return this.items[this.items.length - 1];
}
getMin() {
return this.minimums[this.minimums.length - 1];
}
}
let stack;
const output = [];
for (let index = 0; index < operations.length; index++) {
const operation = operations[index];
if (operation === "MinStack") {
stack = new MinStack();
output.push(null);
} else if (operation === "push") {
stack.push(values[index][0]);
output.push(null);
} else if (operation === "pop") {
stack.pop();
output.push(null);
} else if (operation === "top") {
output.push(stack.top());
} else {
output.push(stack.getMin());
}
}
return output;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Across n operations, dynamic-array pushes and pops take amortized O(1) time each. getMin and top each read a single slot. |
| Auxiliary space | O(n) | The value and minimum stacks can each hold up to n values. |