![]() |
VOOZH | about |
Given an array of size n and multiple values around which we need to left rotate the array. How to quickly find 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 1Input: arr[] = {1, 3, 5, 7, 9}
k1 = 14
Output: 9 1 3 5 7
Simple Approach: We have already discussed different approaches given in the below posts.
The best of the above approaches take O(n) time and O(1) extra space.
Simple Approach: We are using the reverse algorithm but this time for multiple k values - you can click on the above link to understand this approach.
Implementation:
5 7 9 1 3 7 9 1 3 5 9 1 3 5 7
Time Complexity: O(n)
Auxiliary Space: O(n)
Efficient Approach:
The above approaches work well when there is a single rotation required. The approaches also modify the original array. To handle multiple queries of array rotation, we use a temp array of size 2n and quickly handle rotations.
Implementation:
5 7 9 1 3 7 9 1 3 5 9 1 3 5 7
Time Complexity: O(n)
Note that the task to find starting address of rotation takes O(1) time. It is printing the elements that take O(n) time.
Auxiliary Space: O(n)
Space-optimized Approach: The above method takes extra space. Below given is a space-optimized solution. Thanks to frenzy77 for suggesting this approach.
Implementation:
5 7 9 1 3 7 9 1 3 5 9 1 3 5 7
Time Complexity: O(n)
Auxiliary Space: O(1)