I was solving Increasing Subsequences in LeetCode and it is giving error continuously.
Tried in different IDEs with same test cases working every time. Even after brainstorming for an hour or two I was unable to find the error. Here is my C solution.
class Solution {
public:
vector<vector<int>>ans;
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<int>prev;
calc(nums,prev,0);
return ans;
}
void calc(vector<int>&v, vector<int>&prev, int k)
{
if(prev.size()>1)
ans.push_back(prev);
if(k<v.size())
{
unordered_set<int>s;
for(int i = k; i < v.size(); i )
{
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
{
prev.push_back(v[i]);
calc(v,prev,i 1);
s.insert(v[i]);
prev.pop_back();
}
}
}
}
};
Can anyone please help. Showing error in multiple test cases.
Here I am sharing one of the test cases : [4,6,7,7]
Error : Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000110 overflowed to 0x60200000010c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:1043:34
Here is the code which is working in IDEs.
#include <bits/stdc .h>
using namespace std;
vector<vector<int>>ans;
void calc(vector<int>&v, vector<int>&prev, int k)
{
if(prev.size()>1)
ans.push_back(prev);
if(k<v.size())
{
unordered_set<int>s;
for(int i = k; i < v.size(); i )
{
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
{
prev.push_back(v[i]);
calc(v,prev,i 1);
s.insert(v[i]);
prev.pop_back();
}
}
}
}
int main() {
vector<int>nums{4,6,7,7};
vector<int>prev;
calc(nums,prev,0);
for(auto i : ans)
{
for(auto j : i)
cout<<j<<" ";
cout<<endl;
}
}
CodePudding user response:
I was not able to reproduce the santizer message with the input in the question (see https://godbolt.org/z/j4rxGdoYb). However, this condition may wrap around an unsigned integer:
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
When prev.size() == 0
but !s.count(v[i])
is false
then prev.size() -1
subtracts 1
from an unsigned 0
.
Either use std::ssize
to get a signed size. Or make sure that prev[prev.size()-1]
is only evaluated when prev.size() != 0
.
Moreover, the member ans
is never cleared. I expect to get the wrong answer when you call findSubsequences
the second time. Also findSubsequences
should not take the vector by non-const reference when it does not modify it.