I am trying to solve this problem in hackerrank.
https://www.hackerrank.com/challenges/circular-array-rotation/problem
Every other test is fine but one test is creating Segmentation Fault. This is the test case:
https://hr-testcases-us-east-1.s3.amazonaws.com/1884/input04.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1648127766&Signature=a0c1UvQ4t9DBn%2Fkr02ZnLUurhjk%3D&response-content-type=text%2Fplain
I wish to what part of my code is creating Segmentation Fault and I want to know the way to solve it with code and some explanation well as I believe my code should not have created any. Here is my code:
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
rotate(a.begin(),a.begin()+a.size()-k,a.end());
vector<int> result;
cout<<result.size()<<endl;
for(auto x:queries) result.push_back(a[x]);
return result;
}
This is the code I am submitting in the hackerrank solution. Please help me to pass the test.
The problem is:
rotate(a.begin(),a.begin()+a.size()-k,a.end());
According to the problem statement, the constraints are:
1 <= n <= 10^5
1 <= k <= 10^5
There is no constraint that k <= n, and the test case you got there is exactly the hit, n = 515, k = 100000.
So the problem is:
a.begin()+a.size()-k // a.size()-k, when k > n, is negative
So the hackerrank compiler has a problem while it's doing a.begin() - negative num.
For fixing that you should make sure it won't go in negative bounds, and since it's a circular rotation one full rotation or 1000 full rotations won't change anything, only the remainder matters:
rotate(a.begin(), a.begin() + a.size() - (k % a.size()), a.end());
It passes all the test cases.