Open In App

Rotate Array By One

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
305 Likes
Like
Report

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]

Shifting Each Element - O(n) Time and O(1) Space

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.

C++14
C Java Python C# JavaScript

Output
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.

Using Two Pointers - O(n) Time and O(1) 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.

C++14
C Java Python C# JavaScript

Output
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.

Reversing the Array - O(n) Time and O(1) Space

We can use Reversal Algorithm also, reverse first n-1 elements and then whole array which will result into one right rotation.

C++14
C Java Python C# JavaScript

Output
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.


Program to cyclically rotate an array by one
Practice Tags :

Similar Reads