![]() |
VOOZH | about |
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:
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:
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-
Code-
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.