In this post, we will see how to right-rotate an array by specified positions. For example, right rotating array { 1, 2, 3, 4, 5, 6, 7 } three times will result in array { 5, 6, 7, 1, 2, 3, 4 }.

Practice this problem

1. Rotating k times

The idea is to right-rotate all array elements by one position k times, where k is the given rotation count. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

5, 6, 7, 1, 2, 3, 4

Java


Download  Run Code

Output:

[5, 6, 7, 1, 2, 3, 4]

Python


Download  Run Code

Output:

[5, 6, 7, 1, 2, 3, 4]

The time complexity of the above solution is O(n.k), where n is the size of the input and k is the rotation count.

2. Using Auxiliary Array

We can reduce the time complexity of the above solution to linear using some extra space. The idea is to store the last k elements of the input array in an auxiliary array of size k. Then shift the first n-k elements of the input array at the end. Finally, put elements of the auxiliary array at their correct positions in the input array.

Following is the implementation in C, Java, and Python based on the above idea:

C


Download  Run Code

Output:

5, 6, 7, 1, 2, 3, 4

Java


Download  Run Code

Output:

[5, 6, 7, 1, 2, 3, 4]

Python


Download  Run Code

Output:

[5, 6, 7, 1, 2, 3, 4]

The time complexity of the above solution is O(n), and the auxiliary space used is O(k).

3. By reversing array

We can even solve this problem in O(n) time and O(1) extra space. The idea is to reverse the last k elements of the input array and then reverse the remaining n-k elements. Finally, get the right-rotated array by reversing the complete array.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

5, 6, 7, 1, 2, 3, 4

Java


Download  Run Code

Output:

[5, 6, 7, 1, 2, 3, 4]

Python


Download  Run Code

Output:

[5, 6, 7, 1, 2, 3, 4]

Exercise: Left rotate an array k times.