constructor() {
this.stack = [];
this.minStack = [];
}
push(val) {
if (typeof val !== 'number' || isNaN(val)) {
throw new Error('Value should be a number!');
}
this.stack.push(val);
if (this.minStack.length === 0 || val <= this.minStack[this.minStack.length - 1]) {
this.minStack.push(val);
}
}
pop() {
if (this.stack.length === 0) {
throw new Error('Stack is empty');
}
const val = this.stack.pop();
if (val === this.minStack[this.minStack.length - 1]) {
this.minStack.pop();
}
return val;
}
getMin() {
if (this.minStack.length === 0) {
throw new Error('Stack is empty');
}
return this.minStack[this.minStack.length - 1];
}
}
Click Run to execute JavaScript.
Code runs in an isolated environment.
Code runs in an isolated environment.