Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.push(val)pushes the elementvalonto the stack.pop()removes the element on the top of the stack.top()gets the top element of the stack.getMin()retrieves the minimum element in the stack.
You must implement push, pop, top, and getMin in constant time.
Solution
Section titled “Solution”To get the minimum element in constant time, we can use the stack to not only store the elements, but also the minimum element at the time of insertion. This way, we can always get the minimum element in constant time.
Implementation
Section titled “Implementation”class MinStack { constructor() { this.stack = []; }
push(val) { const min = this.stack.length === 0 ? val : Math.min(val, this.getMin()); this.stack.push({ val, min }); }
pop() { this.stack.pop(); }
top() { return this.stack.at(-1).val; }
getMin() { return this.stack.at(-1).min; }}interface StackNode { val: number; min: number;}
class MinStack { private stack: StackNode[];
constructor() { this.stack = []; }
push(val: number): void { const min = this.stack.length === 0 ? val : Math.min(val, this.getMin()); this.stack.push({ val, min }); }
pop(): void { this.stack.pop(); }
top(): number { return this.stack.at(-1).val; }
getMin(): number { return this.stack.at(-1).min; }}Pseudocode
Section titled “Pseudocode”- Create a class
MinStackthat initializes a stack. - Implement
pushmethod that takes a value and pushes it to the stack.- If the stack is empty, set the minimum value to the value being pushed.
- Otherwise, set the minimum value to the minimum of the value being pushed and the current minimum value.
- Implement
popmethod that pops the top element from the stack. - Implement
topmethod that returns the top element from the stack. - Implement
getMinmethod that returns the minimum element from the stack.
Complexity Analysis
Section titled “Complexity Analysis”- The time complexity for all the operations is
O(1)because we are using the stack to store the minimum element. - The space complexity is
O(n)wherenis the number of elements in the stack.