![]() |
VOOZH | about |
Given an array, the task is to cyclically right-rotate the array by one.
Examples:
Input: arr[] = [1, 2, 3, 4, 5]
Output: [5, 1, 2, 3, 4]Input: arr[] = [2, 3, 4, 5, 1]
Output: [1, 2, 3, 4, 5]
Table of Content
The basic idea is to store the last element in a temp variable and shift every other element one position ahead. After shifting, update the first element with value stored in temp.
5 1 2 3 4
Time Complexity: O(n), as we need to iterate through all the elements. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are using constant space.
We can use two pointers, As we know in cyclic rotation we will bring last element to first and shift rest in forward direction, we can do this by swapping every element with last element till we get to the last point.
5 1 2 3 4
Time Complexity: O(n), as we need to iterate through all the elements. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are using constant space.
We can use Reversal Algorithm also, reverse first n-1 elements and then whole array which will result into one right rotation.
5 1 2 3 4
Time Complexity: O(n), as we are reversing the array. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are using constant space.