In this post, we will see how to left-rotate an array by specified positions. For example, left-rotating array { 1, 2, 3, 4, 5 } twice results in array { 3, 4, 5, 1, 2 }.

Practice this problem

1. Rotating r times

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

C


Download  Run Code

Output:

3 4 5 1 2

Java


Download  Run Code

Output:

[3, 4, 5, 1, 2]

Python


Download  Run Code

Output:

[3, 4, 5, 1, 2]

The time complexity of the above solution is O(n.r), where n is the size of the input and r 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 first r elements of the input array in an auxiliary array of size r. Then shift the remaining n-r elements of the input array at the beginning. Finally, put elements of the auxiliary array at their correct positions in the input array.

C


Download  Run Code

Java


Download  Run Code

Output:

[3, 4, 5, 1, 2]

Python


Download  Run Code

Output:

[3, 4, 5, 1, 2]

The time complexity of the above solution is O(n), where n is the size of the input. The auxiliary space required by the program is O(r), where r is the rotation count.

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 first r elements of the input array and then reverse the remaining n-r elements. Finally, get the left-rotated array by reversing the complete array.

C


Download  Run Code

Output:

3 4 5 1 2

Java


Download  Run Code

Output:

[3, 4, 5, 1, 2]

Python


Download  Run Code

Output:

[3, 4, 5, 1, 2]

Exercise: Modify above methods to right-rotate the array by r positions.