Search code examples
c++compiler-errorscompilationtestcase

Problem with c++ leetcode compiler while compile a code { local compiler and online compiler gives different result for the same code }


This is the problem i am trying to solve, along with the solution testing the test case in which i am having trouble in.

Leetcode problem: 128. Longest Consecutive Sequence

#include <iostream>
#include <vector>
#include <unordered_map>

class Solution {
public:
    int longestConsecutive(std::vector<int>& nums)
    {
        std::unordered_map<int, int> seq;
        for (auto i : nums)
        {
            ++seq[i];
        }
        int max{ 0 };
        for (auto i : seq)
        {
            int ans{ 0 };
            int x{ i.first };
            if (seq[x] > 0)
            {
                ans = 1;
                int p{ x };
                int q{ x };
                while (seq[p - 1] > 0)
                {
                    --p;
                    ++ans;
                }
                while (seq[q + 1] > 0)
                {
                    ++q;
                    ++ans;
                }
            }
            if (max < ans)
                max = ans;
        }
        return max;
    }
};

int main()
{
    Solution s;
    std::vector<int> nums{ 4,0,-4,-2,2,5,2,0,-8,-8,-8,-8,-1,7,4,5,5,-4,6,6,-3 };
    std::cout << s.longestConsecutive(nums);
    return 0;
}

When i tested this test case in my offline compiler(microsoft c++ compiler in visualt studio), it is showing the test case ans as 5(which is absolutely correct).

microsoft visual studio debug console screenshot

However, upon submitting the same solution in leetcode it is showing the test case ans as 4(which is wrong). I tried testing this case in online gdb compiler also and there also this test case ans is showing as 4.

Leetcode failed test case screenshot

My solution has passed 55/72 cases so i am sure there is not any issue with my algorithm or my answer output format. I believe it to be an issue with leetcode or online


Solution

  • Consider your code (shortened for brevity)

        for (auto i : seq)
        {
            int x{ i.first }; 
            if (seq[x] > 0) // okay, will be in the sequence
            {
                int p{ x };
                int q{ x };
                while (seq[p - 1] > 0) // p-1 might not be in the map, so insert
                {}
                while (seq[q + 1] > 0) // q+1 might not be in the map, so insert
                {}
            }
        }
    

    Both these while loops can cause insertions, which can invalidate the iterators used by for (auto i : seq). Thus, you have Undefined Behaviour, and getting anywhere near the correct result is more by accident.