21
Jan
2020

Hackerrank Circular Array Rotation (C++)

C++ :

vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
    vector<int> rotated;
    int timesToRotate = 0;

    k = k % a.size();
    timesToRotate = a.size() - k;

    rotate(a.begin(), a.begin() + timesToRotate, a.end());

    for(int i = 0; i < queries.size(); i++){
        rotated.push_back(a[queries[i]]);
    }

    return rotated;
}

Explanation:

This question involved rotating the elements in a vector. The good thing is, C++ has a nice little in-built function to do that.

First, we take mod k by a.size(), to ensure that k would not be greater than a.size() when using the rotate function of C++. This will get the remainder of k / a.size() (integer division). Then, we calculate the number which should appear at the start of the vector for the rotate function by using a.size() – k and assigning it to timesToRotate.

This is according to the example, such that the rotation begins at the back instead of the front. For example, [1, 2, 3] rotating twice would be [3, 1, 2], then [2, 3, 1], so we use a.size() – k to ‘rotate’ from the back.

The rotate function takes 3 parameters in this case: beginning of the vector to rotate, which element to rotate to, and end of the vector to rotate to. This function is very flexible, such that you can only parts of the vector, leaving the beginning and ending of the vector untouched., but they would be pushed back due to the element to rotate to being pushed to the front.

After rotation, we push the elements of the rotated vector a into an empty vector rotated according to the sequence in queries vector.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *