You are given an integer array of size N. Your task is to rotate the array by one position in the clockwise direction.
For example :If N = 5 and arr[ ] = {1, 2, 3, 4, 5} then output will be 5 1 2 3 4.
If N = 8 and arr[ ] = {9, 8, 7, 6, 4, 2, 1, 3} then output will be 3 9 8 7 6 4 2 1.
Input format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
Then the T test cases follow.
The first line of each test case contains an integer ‘N’, the length of the array.
The second line of each test case contains N space-separated integers denoting the elements of the array.
Output format :
For each test case, printed the rotated array.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given functions.
1 <= T <= 5
1 <= N <= 1000
-10^9 <= arr[i] <=10^9
1
5
1 2 3 4 5
5 1 2 3 4
The first four elements are shifted towards the right by one position, and the last element i.e. 5 is shifted to the first position.
1
8
9 8 7 6 4 2 1 3
3 9 8 7 6 4 2 1
Think about shifting the elements of the array one position ahead.
In this approach, we will first store the last element of the array in a variable let's say ‘x’. Now, shift all the elements one position to the right-hand side or in a clockwise direction. Finally, replace the first element of the array with ‘x’.
Algorithm:
O(N), where N is the length of the array.
As we are traversing the array only once.
O(1)
Constant extra space is required.