Min Stack

Medium#155value + minimum

Build a stack with push, pop and top that also answers getMin, the smallest value in it, and every call has to take O(1) time. pop, top and getMin are only called on a stack that is not empty. Our example: push(5), push(3), push(7), push(3), getMin(), pop(), getMin(), pop(), pop(), getMin(), top(). The four answers are 3, 3, 5 and 5.

input
Calls one after another: MinStack() makes an empty stack, then push(val), pop(), top() and getMin() in any order.
returns
top() returns the item on top, getMin() the smallest item in the stack; push and pop return nothing (null in the output). LeetCode wants each call in O(1).
constraints
  • 2 ≤ calls ≤ 2000
  • −2³¹ ≤ val ≤ 2³¹ − 1
  • pop, top and getMin are called only on a stack that is not empty
our 9 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
var MinStack = function() {

};

/**
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function(val) {

};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {

};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {

};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {

};

/**
 * 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()
 */
Ctrl ↵
format
reset

saved in this browser

9 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more stack problems

Pattern “Stack” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.