Solved Problem - Rotate Array

In this lesson, we'll see how to rotate an array.

Problem statement

Given an array, A[]A[] of length NN. Rotate it clockwise by dd or cyclic shift the element to the right by dd. Input format

The first line consists of two space-separated integers N,dN,d (1N105)(1 \leq N \leq 10^5).

The second line consists of NN space-separated integers representing the array A[]A[] (1A[i]105)(1 \leq A[i] \leq 10^5).


Sample

Input:

8 3
1 2 3 4 5 6 7 8

Output

6 7 8 1 2 3 4 5

Solution

Let’s see what happens when we cyclic shift by one. The last element comes to the first place and each other element moves one place to the right. We can do this dd times. The complexity of this solution would be O(Nd)O(Nd).

We can optimize it further based on the observation that after dd operation, the last dd elements become the first dd elements and the remaining NdN-d elements each shift to the right by dd places. We can do that in a single go.

Get hands-on with 1200+ tech skills courses.