Stack With O(1) Minimum
Track the minimum of a numeric stack in constant time using a parallel minimum stack, without scanning elements.
Code
export class MinStack {
#values = [];
#minimums = [];
push(value) {
if (typeof value !== "number" || Number.isNaN(value)) {
throw new TypeError("value must be a number");
}
this.#values.push(value);
const currentMin = this.#minimums.length > 0
? this.#minimums[this.#minimums.length - 1]
: Infinity;
this.#minimums.push(Math.min(value, currentMin));
return this;
}
pop() {
if (this.#values.length === 0) return undefined;
this.#minimums.pop();
return this.#values.pop();
}
peek() {
return this.#values[this.#values.length - 1];
}
min() {
return this.#minimums[this.#minimums.length - 1];
}
get size() {
return this.#values.length;
}
toArray() {
return [...this.#values];
}
}How the snippet works
Count the class MinStack as the entire surface area of Stack With O(1) Minimum.
TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
A fresh value is allocated for the result; the arguments stay untouched.
What to watch for
- The guard
this.#values.length === 0short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Import MinStack from the file and call it — the rest of the code is implementation detail.
Statements that matter
return this.#minimums[this.#minimums.length - 1];
if (this.#values.length === 0) return undefined;
throw new TypeError("value must be a number");
Interactive Tools for This Topic
FAQ
- Does `MinStack` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- How does the code behave when input is bad?
- The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.