Share my Python solution using pair to store element and current min


  • 2
    D

    The idea is to use pair (element, currentMin) to store element and the minimum at the time element is pushed onto stack

    class MinStack:
        def __init__(self):
            self.stack = []
    
        # @param x, an integer
        # @return an integer
        def push(self, x):
            currentMin = self.getMin()
            if currentMin is None or x < currentMin:
                currentMin = x
            self.stack.append((x, currentMin))
            return x
    
        # @return nothing
        def pop(self):
            self.stack.pop()
    
        # @return an integer
        def top(self):
            return self.stack[-1][0]
    
        # @return an integer
        def getMin(self):
            return None if not self.stack else self.stack[-1][1]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.