Cyclically Rotate An Array By One

Easy
0/40
Average time to solve is 10m
profile
Contributed by
18 upvotes
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.
Detailed explanation ( Input/output format, Notes, Images )

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

Sample Input 1 :

1
5
1 2 3 4 5

Sample Output 1 :

5 1 2 3 4

Explanation For Sample Input 1 :

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.

Sample Input 2 :

1
8
9 8 7 6 4 2 1 3

Sample Output 2 :

3 9 8 7 6 4 2 1
Hint

 Think about shifting the elements of the array one position ahead.

Approaches (1)
Brute-Force

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.
Time Complexity

O(N), where N is the length of the array.

 

As we are traversing the array only once.

Space Complexity

O(1)

 

Constant extra space is required.

Code Solution
(100% EXP penalty)
Cyclically Rotate An Array By One
Full screen
Console