Looking at the inputs, I don't see how this wrong output is possible

  • 0

    To confirm my sanity, I tested the same inputs on my local machine and got the correct answer.
    The missed test case is literally push(-1) and then check the top and min, which should be -1.
    Somehow, my code is producing a -3. Could it be a leftover from a previous test case that wasn't cleaned up?

    Here's the wrong answer result:

    Input:	push(-1),top,getMin
    Output:	[-1,-3]
    Expected:	[-1,-1]

    Here's my code:

    class minPair:
        count = 1
        num = 0
        def __init__(self, min):
            self.num = min
    class MinStack:
        allStack = list()
        minStack = list()
        # @param x, an integer
        # @return an integer
        def push(self, x):
            if len(self.minStack) == 0 or x < self.minStack[-1].num:
            elif x == self.minStack[-1].num:
                self.minStack[-1].count += 1
            return x
        # @return nothing
        def pop(self):
            if len(self.allStack) > 0:
                result = self.allStack.pop()
                if self.minStack[-1].num == result:
                    if self.minStack[-1].count > 1:
                        self.minStack[-1].count -= 1
                        return self.minStack.pop().num
        # @return an integer
        def top(self):
            if len(self.allStack) > 0:
                return self.allStack[-1]
        # @return an integer
        def getMin(self):
            if len(self.minStack) > 0:
                return self.minStack[-1].num

  • 2

    Note that any variable defined in the class but not in any of its member function is a static variable, meaning that it does not need any class instance to exist, and all instances of that class share THE ONLY copy of this variable.

    In your class, allStack and minStack are such static variables, so of course their values are subject to pollution when multiple instances of MinStack exist.

    You should write your own _init_ function and put the definition of the two variables in there.

  • 0

    Ah! Guess I didn't know enough about python! Thanks!

Log in to reply

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