OJ Bug in Python?


  • 0
    M

    I'v implemented this in Python at first but I got this strange error from the OJ (cannot reproduce locally):

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

    I believe this should be a problem of OJ because I rewrite the same algorithm in C++ and get Accepted.


  • 7

    You are initializing the variables as class variables. As OJ runs all test cases in one go, the static variables preserved its previous states and caused issues.

    class MinStack:
        # the stack it self
        stack = []
        # the stack to store (depth, min)
        minstack = []
    

    Try to initialize the variables in the constructor instead, which defines them as instance variables:

    class MinStack:
        def __init__(self):
            # the stack it self
            self.stack = []
            # the stack to store (depth, min)
            self.minstack = []
    

    Read more about the difference between class variables and instance variables here: http://stackoverflow.com/questions/2714573/instance-variables-vs-class-variables-in-python


  • 0
    M

    Thanks, I missed the "in one go". I think this might be an exploit of Python. For problems like fibonacci, python can utilize the previous results to reduce the time consumption. Is it unfair to other languages or just a small bonus to Python c0d3rs?


  • 0

    Nope, other languages could declare static variables as well, or even global variables to save states across all test cases.


Log in to reply
 

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