30 March 2024
Medium
155. Min Stack
Link: https://leetcode.com/problems/min-stack
Description: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Solution:
Create two stacks: one to store the elements and another to store the minimum elements. When pushing an element onto the stack, check if it is less than or equal to the current minimum element. If it is, push the element onto the minimum stack. When popping an element, check if it is the minimum element and pop it from the minimum stack if it is. The top and getMin functions can then return the top elements of the stack and minimum stack, respectively.
var MinStack = function () {
this.stack = []
this.minStack = []
}
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function (val) {
this.stack.push(val)
if (this.minStack.length === 0 || val <= this.getMin()) {
this.minStack.push(val)
}
}
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
if (this.stack.pop() === this.getMin()) {
this.minStack.pop()
}
}
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.stack[this.stack.length - 1]
}
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
return this.minStack[this.minStack.length - 1]
}
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(val)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/