1

Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }

The remaining code can be found here link

IshduttT
  • 179
  • 1
  • 14

3 Answers3

1

Quality of the implementation aside (there is no need to make any copy to rotate a vector, it can be done in-place), most probably the error causing the segfault is in the code that's not shown.

To debug this further the following links might be of use:

If you need further assistance, post your entire code.

== EDIT ==

Your code isn't triggering a segfault but a "Terminated due to timeout" error on HackerRank. In other words, your solution is too slow.

That's because there is no need to rotate anything to solve Circular Array Rotation:

vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
    vector<int> res;
    res.reserve(queries.size());
    int offset = k % a.size() - a.size();
    for (int i : queries) {
        res.push_back(a[(i - offset) % a.size()]);
    }
    return res;
}

i.e. just take the rotation into account when selecting the requested element.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Only this function was written by me and all the other was prewritten.It can be found here [link](https://www.hackerrank.com/challenges/circular-array-rotation/problem) – IshduttT May 27 '19 at 08:07
  • You should have posted that link in the question. See my updated answer. – rustyx May 27 '19 at 10:31
  • It showed segmentation fault error on my machine. Anyways thanks for pointing the mistake – IshduttT May 27 '19 at 11:02
0

A vector is backed by an array of continuous memory, and your machine isn't able to allocate such a large array.

You could consider using a list instead, but would probably need to rewrite the code to use iterators if you care about performance.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

The problem can be queries[k] > a.size() at line result[k]=a[queries[k]]; As we don't know actual inputs, it is really hard to pinpoint the reason.

akib khan
  • 451
  • 4
  • 9