1

This code is producing segmentation fault error in one test case ,please help

the question is circular array rotation from hackkerrank-https://www.hackerrank.com/challenges/circular-array-rotation/problem

vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
       int i,temp;
       vector<int> ans,rotated;
      
       if(k>a.size())   //if rotation is more than array size then same as k=-size
       k=k-a.size();
       //rotating the array k times 
       //i.e last element in first pos and moving the rest at one pos forward
       //but rotaing in more optimised way
        if(k!=a.size()){
            for(i=a.size()-k;i<a.size();i++)
            rotated.push_back(a[i]);
            for(i=0;i<a.size()-k;i++)
            rotated.push_back(a[i]);
        }
        
        for(i=0;i<queries.size();i++)
        {   if(k!=a.size())                  //if rotation is same as array size the array is same
            ans.push_back(rotated[queries[i]]);
            else
            ans.push_back(a[queries[i]]);
        }
        return ans;
    }
Mohammad Atif
  • 83
  • 1
  • 6
  • What happens if `k > 2*a.size()`? Or if `k > 7*a.size()`? I think you need to use the modulus operator, rather than just subtracting `a.size()` *once*. – Adrian Mole Jun 27 '20 at 12:28
  • 1
    What is a segmentation fault? [This answer](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) might help. –  Jun 27 '20 at 12:30
  • @AdrianMole Thanks buddy..I replaced the if(k>a.size()) with while(k>a.size()){ k=k-a.size(); } and the problem is solved.. – Mohammad Atif Jun 27 '20 at 12:41

0 Answers0