Rotate an array to the right by a given number of steps.

Hello

The following code snippet is serving the purpose, but not fully I guess - it is supposed to shift each element of the array to the right by K number of times

1
2
3
4
5
6
7
8
vector<int> solution(vector<int> &A, int K)
{
   
    if(A.size() > 1 && K >= 0 )
      std::rotate(A.rbegin(), A.rbegin() + K, A.rend());

    return A;
}


How to deal with the scenario if K >= A.size() ? In other words the number of shifting to the right is greater than or equal to the size of the array . It does not work with this input and returns the very same array .

Any thoughts ?

Thanks
Don't shift K steps; shift (k%A.size()) steps.

That is, if the size is 5 and K is 5, shift 0 steps.
If the size is 5 and K is 6, shift 1 step.
If the size is 5 and K is 7, shift 2 steps.
If the size is 5 and K is 8, shift 3 steps.
...
If the size is 5 and K is 28, shift 3 steps.

1
2
3
4
5
6
7
8
vector<int> solution(vector<int> &A, int K)
{
   
    if(A.size() > 1 && K >= 0 )
      std::rotate(A.rbegin(), A.rbegin() + K%A.size(), A.rend());

    return A;
}
Topic archived. No new replies allowed.