Last Updated: 29 Jan, 2021

Cyclically Rotate An Array By One

Easy
Asked in companies
IBMRTDSDeloitte

Problem statement

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.
Constraints :
1 <= T <= 5
1 <= N <= 1000
-10^9 <= arr[i] <=10^9

Approaches

01 Approach

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:

 

  • Store the last element of the array in a variable say x.
  • Shift all elements one position to the right-hand side (clockwise rotation).
  • Replace the first element of the array with x.