Design a stack that supports push, pop, and top operations and can retrieve the smallest element in constant time.

Push (x) – Pushes the element X onto the stack. Pop () – Removes the top element of the stack. Top () – Gets the top element on the stack. GetMin () – Retrieves the smallest element in the stack. Example:

MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); –> return -3.minstack.pop (); minStack.top(); –> return 0. Minstack.getmin (); — — > to return to 2.

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.all = []

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.all.append(x)

    def pop(self):
        """
        :rtype: None
        """
        del self.all[-1]

    def top(self):
        """
        :rtype: int
        """
        return self.all[-1]
        

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.all)
        


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
Copy the code