You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Implement Min Stack, min stack is same as normal stack but, it has function that return the min value of stack.
Min Stack has to have push, pop, getMin, top methods, each method has a time complexity of O(1).
Approach
Managing values in stack, and minStack.
minStack is used for saving values those are less than getMin() or same.
The code is below.
/** * Stack = [-2] * minStack = [-2] * * Stack = [-2, 0] * minStack = [-2] Zero is not pushed to minStack, because 0 is not less than getMin(). * * Stack = [-2, 0, -3] * minStack = [-2, -3] minValues is managed by minStack. * * Stack = [-2, 0] * minStack = [-2] * * Stack = [-2, 0, -3] * minStack = [-2, -3] * * Stack = [-2, 0, -3, -3] * minStack = [-2,-3,-3] Value is pushed to minStack when value is less than getMin() OR same as. * * Stack = [-2, 0, -3] * minStack = [-2,-3] minStack value is poped when stack is poped and the value is same as getMin(). * */constMinStack=function(){this.stack=[];this.minStack=[];};/** * @param {number} val * @return {void} */MinStack.prototype.push=function(val){this.stack.push(val);constcurrentMin=this.getMin();if(currentMin===null||currentMin>=val){this.minStack.push(val);}};/** * @return {void} */MinStack.prototype.pop=function(){constpopedValue=this.stack.pop();if(popedValue===this.getMin()){this.minStack.pop();}};/** * @return {number} */MinStack.prototype.top=function(){returnthis.stack[this.stack.length-1];};/** * @return {number} */MinStack.prototype.getMin=function(){if(this.minStack.length===0){returnnull;}returnthis.minStack[this.minStack.length-1];};
The text was updated successfully, but these errors were encountered:
Problem
Implement Min Stack, min stack is same as normal stack but, it has function that return the min value of stack.
Min Stack has to have push, pop, getMin, top methods, each method has a time complexity of O(1).
Approach
Managing values in stack, and minStack.
minStack is used for saving values those are less than getMin() or same.
The code is below.
The text was updated successfully, but these errors were encountered: