You are given an array A of size N.
You are also given an integer X and a direction DIR. You need to rotate the array A by X positions in the direction specified by DIR.
DIR can be:
Return the resulting rotated array.
For example:
Input :
A = [6, 2, 6, 1], X = 1, DIR = ‘LEFT’
Output :
2 6 1 6
Explanation: Rotate array ‘A’ to the left one time.
[6, 2, 6, 1] => [2, 6, 1, 6]
First-line contains 'T,' denoting the number of Test cases.
For each Test case:
The first line contains two integers, ‘N', ‘X’, and the string ‘DIR’.
The second line has ‘N’ integers denoting the array ‘A’.
Output Format:-
You must return the rotated array.
Note:-
You don’t need to print anything. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
1 <= X <= 10^9
‘DIR’ is an element of {‘LEFT’, ‘RIGHT’}
Time Limit: 1 sec
2
4 1 LEFT
1 2 3 4
6 2 RIGHT
1 2 4 3 5 6
2 3 4 1
5 6 1 2 4 3
For test case one:
Input :
A = [1, 2, 3, 4], X = 1, DIR = ‘LEFT’
Output :
2 3 4 1
Explanation: Rotate array ‘A’ to the left one time.
[1, 2, 3, 4] => [2, 3, 4, 1]
For test case two:
Input :
A = [1, 2, 4, 3, 5, 6], X = 2, DIR = ‘RIGHT’
Output :
5 6 1 2 4 3
Explanation: Rotate array ‘A’ to the right one time.
[1, 2, 4, 3, 5, 6] => [6, 1, 2, 4, 3, 5]
2
6 3 LEFT
22 8 4 7 5 10
6 2 RIGHT
9 3 1 6 3 9
7 5 10 22 8 4
3 9 9 3 1 6
Observe how the element's position changes after rotation.
Approach:
Algorithm:
Function void rotateLeft([int] A):
Function void rotateRight([int] A):
Function [int] rotateArray([int] A, int X, string DIR):
O( N * X ), Where ‘N’ is the size of the array ‘A’ and ‘X’ is the number of rotations.
We are taking O( N ) to perform one rotation. We take O( N * X ) time to achieve' X' rotations. Hence, the overall complexity will be O( N * X ).
O( 1 ).
We are using constant extra space. So, the Space Complexity is O( 1 ).