Python solution with detailed explanation


  • 0
    G

    Solution

    Min Stack https://leetcode.com/problems/min-stack/

    • Store the minimum value so far along with the value on a stack.
    class MinStack(object):
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.st = []
    
        def push(self, x):
            """
            :type x: int
            :rtype: nothing
            """
            if len(self.st) == 0:
                self.st.append((x,x))
            else:
                min_so_far = min(x, self.st[-1][1])
                self.st.append((x, min_so_far))
    
        def pop(self):
            """
            :rtype: nothing
            """
            self.st.pop()
            return
    
        def top(self):
            """
            :rtype: int
            """
            return self.st[-1][0]
            
    
        def getMin(self):
            """
            :rtype: int
            """
            return self.st[-1][1]
    

Log in to reply
 

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