Programming problem: Min Stack
Maintain two stacks in parallel: one for values and one tracking the current minimum at each level. This makes `getMin` O(1) instead of scanning the full stack, and avoids rebuilding the array on every `pop`.
Question
Design a stack class that supports the push, pop, top, and getMin operations.
MinStack()initializes the stack object.void push(int val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack.
Each function should run in O(1) time.
Example
Input: ["MinStack", "push", 1, "push", 2, "push", 0, "getMin", "pop", "top", "getMin"]
Output: [null,null,null,null,0,null,2,1]
Explanation:
MinStack minStack = new MinStack();
minStack.push(1);
minStack.push(2);
minStack.push(0);
minStack.getMin(); // return 0
minStack.pop();
minStack.top(); // return 2
minStack.getMin(); // return 1
Constraints
-2^31 <= val <= 2^31 - 1.pop,topandgetMinwill always be called on non-empty stacks.
Solution
class MinStack {
value: number[] = [];
push(val: number): void {
this.value[this.value.length] = val;
}
pop(): void {
const nextValue: number[] = [];
for (let i = 0; i < this.value.length - 1; i++) {
nextValue[i] = this.value[i];
}
this.value = nextValue;
}
top(): number {
return this.value[this.value.length - 1];
}
getMin(): number {
let min: number = this.value[0];
for (const val of this.value) {
min = Math.min(min, val);
}
return min;
}
}