Problem Description

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. void push(int val) pushes the element val onto 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. You must implement a solution with O(1) time complexity for each function.

Example 1:

  • Input: MinStack(),push(-2), push(0), push(-3),getMin(),pop(),top(),getMin()
  • Output: -3,0,-2

My Idea

The main hurdle in implementing this stack is to get the min element in constant time. In order to do that and not increase the space complexity, when adding an element to the stack, we instead add a tuple (e,min), which contains the element and the minimum element at the time of addition. This requires constant time, since it’s just one comparison. It also makes sure that the minimum element doesn’t need to be calculated after popping a value. The other operations are trivial.

My solution

class MinStack:

    def __init__(self):
        self.stack = []

    def push(self, val: int) -> None:
        if self.stack==[]:
            self.stack.append((val,val))
        else:
            self.stack.append((val,min(val,self.stack[-1][1])))



    def pop(self) -> None:
        self.stack = self.stack[:-1]


    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]