Cyclically rotate an array by one
Problem​
Given an array, rotate the array by one position in clock-wise direction.
Examples:​
Example 1:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
5 1 2 3 4
Example 2:
Input:
N = 8
A[] = {9, 8, 7, 6, 4, 2, 1, 3}
Output:
3 9 8 7 6 4 2 1
Your task:​
You don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array in place.
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:​
Solution​
Python​
def rotate( arr, n):
last_el = arr[n - 1]
for i in range(n - 1, 0, -1):
arr[i] = arr[i - 1]
arr[0] = last_el
Java​
public void rotate(int arr[], int n) {
int last_el = arr[arr.length - 1], i;
for (i = arr.length - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = last_el;
}
C++​
void rotate(int arr[], int n) {
int last_el = arr[n - 1];
for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last_el;
}
C​
void rotate(int arr[], int n) {
int last_el = arr[n - 1];
for (int i = n - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = last_el;
}
- Time Complexity:
- Auxiliary Space: