Complete the code to push a value onto the stack.
push(val: number): void {
this.stack.[1](val);
}The push method adds an element to the end of the array, which is how we add to the stack.
Complete the code to get the current minimum value from the min stack.
getMin(): number | null {
if (this.minStack.length === 0) return null;
return this.minStack[[1]];
}The minimum value is always at the top of the minStack, which is the last element. So we access it by index this.minStack.length - 1.
Fix the error in the pop method to correctly update the min stack.
pop(): number | null {
if (this.stack.length === 0) return null;
const val = this.stack.pop();
if (val === this.minStack[[1]]) {
this.minStack.pop();
}
return val;
}We need to compare val with the top element of minStack, which is the last element at index this.minStack.length - 1.
Fill both blanks to correctly update the min stack when pushing a new value.
push(val: number): void {
this.stack.push(val);
if (this.minStack.length === 0 || val [1] this.minStack[[2]]) {
this.minStack.push(val);
}
}We push the new value onto minStack if it is less than or equal to the current minimum. The current minimum is at the last index this.minStack.length - 1.
Fill all three blanks to implement the getMin method safely.
getMin(): number | null {
if (this.minStack.length === 0) return [1];
return this.minStack[[2]];
}
// Usage example:
const minValue = stack.getMin();
if (minValue !== [3]) {
console.log('Minimum:', minValue);
}If the minStack is empty, getMin returns null. The minimum value is at the last index this.minStack.length - 1. When checking the returned value, we compare it to null to avoid errors.
