First, please check if you are using any global or static variables. They are Evil, period. If you must declare one, reset them in the first line of your called method or in the default constructor.
Why? Because the system executes all test cases using the same program instance, global/static variables affect the program state from one test case to another. See this Discuss thread for an example.
If you have checked all over your code and did not find any global/static variables usage, chances are your code has bugs in it which cause one of the earlier test cases to trigger an undefined behavior.
How undefined behavior was triggered could vary from one language to another. We outline the most commonly encountered language-specific behavior below to help you in debugging shall you encounter one.
C/C++
The most frequent culprit causing undefined behavior is out-of-bounds array access. These bugs could be hard to debug, so good luck. Or just give up on C/C++ entirely and code in a more predictable language, like Java. :)
Java
In general, Java is a much safer language and employs some safety checks for you, such as out-of-bounds array access checking. However, even then, it is not 100% foolproof and you could still encounter undefined behavior. A common mistake is using ==
instead of .equals()
for String comparison, which will cause undefined behavior.
Python
First, check if you have any class variables and ensure they are initialized for each test case, not just once for the entire process.
class DisjointSet:
sets = {} # This is only init once per process.
longest = 0 # This is only init once per process.
For the example above, the class DisjointSet has two class variables and are not initialized for each test case and will cause unexpected behavior. The below code will initialize the class variables properly for each test case.
class DisjointSet:
# default constructor, init all member data.
def __init__(self):
self.sets = {} # This is init for each test case.
self.longest = 0 # This is init for each test case.
Another common pitfall is using mutable default arguments. For example, a list or a dict are mutable objects, but a string is an immutable object. As shown below, the user uses a list combinations
as the default argument to a function causing unexpected behavior. Besides causing unexpected behavior, this is an anti-pattern in the real world and you should avoid it.