VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-left-rotation-array/

⇱ Print left rotation of array in O(n) time and O(1) space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print left rotation of array in O(n) time and O(1) space

Last Updated : 5 Dec, 2024

Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations?

Examples :

Input :
arr[] = {1, 3, 5, 7, 9}
k1 = 1
k2 = 3
k3 = 4
k4 = 6
Output :
3 5 7 9 1
7 9 1 3 5
9 1 3 5 7
3 5 7 9 1
Input :
arr[] = {1, 3, 5, 7, 9}
k1 = 14
Output :
9 1 3 5 7

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

We have discussed a solution in the below post. 
Quickly find multiple left rotations of an array | Set 1

Method I: The solution discussed above requires extra space. In this post, an optimized solution is discussed that doesn't require extra space.

Implementation:


Output
5 7 9 1 3 
7 9 1 3 5 
9 1 3 5 7 

Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(1), as we are not using any extra space.

Method II: In the below implementation we will use Standard Template Library (STL) which will be making the solution more optimize and easy to Implement.

Implementation:


Output
5 7 9 1 3 

Note: the array itself gets updated after the rotation.

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

Method III(Using Reversal):

To left rotate an array by "k" units we will perform 3 simple reversals-

  • Reverse the first "k" elements
  • Reverse the last "n-k" elements where n is the size of the array
  • Reverse the whole array

Code-



Output
5 7 9 1 3 

Note: the array itself gets updated after the rotation.

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

Comment
Article Tags: