Time Limited Exceeded for Python solution


  • 0
    A

    I'm getting the Time Limit Exceeded error for this question and I'm not sure why, given that my code is very similar to other solutions posted here. (I've encountered the same issue for several other problems.)

    class MinStack:
        def __init__(self):
            self.items = [] # the elements in the stack
            self.mins = [] # the minimum element at each depth
            
        # @param x, an integer
        # @return an integer
        def push(self, x):
            self.items.append(x)
            if len(self.items) == 1:
                self.mins.append(x)
            elif x < self.mins[-1]:
                self.mins.append(x)
            else:
                self.mins.append(self.mins[-1])
    
        # @return nothing
        def pop(self):
            self.items = self.items[:-1]
            self.mins = self.mins[:-1]
    
        # @return an integer
        def top(self):
            return self.items[-1]
    
        # @return an integer
        def getMin(self):
            return self.mins[-1]
    

    Does anyone see the problem?


  • 0
    A

    UPDATE: Changing the pop method to the following seems to fix the problem:

    def pop(self):
    self.items.pop()
    self.mins.pop()


  • 0
    C

    I have the same problem


Log in to reply
 

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