We know that Leetcode puts the solution function into a class. Let’s check example below:

int gv = 0;
 
class Solution {
public:
    int returnSecondElem(int arr[]) {
        gv += 1;
        cout << gv; // expected to be 1 in each case
        return arr[gv];
    }
};

Here we initialize a global variable gv and use it in the solution function returnSecondElem(). In this case, we may expected that for each test case, the cout << gv will print 1 and the second element of the array is returned.

However, this is not the case. Since gv is global variable, and Leetcode seems to use single Solution instance for solving all test cases, when first test case finished, the gv already became 1, so for the second test case, program will print 2 and third element will be returned.


If we want to use global variable, we may also want to initialize it at the beginning of the solution method:

int gv = 0;
 
class Solution {
public:
    int returnSecondElem(int arr[]) {
        // always initialize here!
        gv = 0;
        gv += 1;
        cout << gv;
        return arr[gv];
    }
};