Simple Python solution (beats 91%)


  • 0
    S
    1. Method: Use two stacks (one for actual stack and one for min value)
    2. Push: When you push a value to main stack push into min value stack only if the value is less than or equal to the current top of min value stack
    3. Pop: When you pop a value if the top of the min value stack is equal to that value, then pop min value too

    class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.minvalue = []
    
    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        if len(self.minvalue)>0:
            if x<=self.minvalue[-1]:
                self.minvalue.append(x)
        else:
            self.minvalue.append(x)      
    
    def pop(self):
        """
        :rtype: void
        """
        p = self.stack.pop()
        if p==self.minvalue[-1]:
            self.minvalue.pop()        
    
    def top(self):
        """
        :rtype: int
        """
        if len(self.stack)>0:
            return self.stack[-1]
    
    def getMin(self):
        """
        :rtype: int
        """
        return self.minvalue[-1]

Log in to reply
 

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