
Performing a 'left rotation' means deleting the first character of the string and appending it to the end of the string.
Performing a 'right rotation' means deleting the last character of the string and appending it to the beginning of the string.
For example, if we perform a left rotation on the string “coding”, it will become “odingc”. If we perform a right rotation on the string “ninja”, it will become “aninj”.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains a single string, 'MESSAGE',
The second line of each test case contains an integer, ‘N’, denoting the number of rotations we need to perform in order to decrypt the message. Then, ‘N’ lines follow.
Each line contains two space-separated integers, ‘A’ and ‘B’. If ‘A’ is ‘-1’, you need to perform the left rotation on the string ‘MESSAGE’, ‘B’ times. If ‘A’ is ‘1’, you need to perform the right rotation, ‘B’ times.
For each test case, return a single string, denoting the decrypted message after performing all the required operations.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |MESSAGE| <= 500
1 <= N <= 1000
N is always even
Time Limit: 1sec
The approach is to observe the fact that if we perform a rotation operation, ’LEN * K’ times, where ‘LEN’ is the length of the string and ‘K’ is an arbitrary number, then we are effectively making no rotation in either direction. So, if we need to perform a rotation operation, ‘X’ number of times, we can perform it ‘X % LEN’ times, and we will still get the same result.
Another observation here is that if we want to perform the left rotation operation, ‘X’ times, then we can simply delete the first ‘X’ characters from the string and append them at the last of the string. Similarly, for the right rotation operation, we can delete the last ‘X’ characters and append them at the beginning of the string.
We can observe that making some rotation operations in one direction and making the same number of rotation operations in the opposite direction effectively means making no rotations at all. So, we can calculate the effective number of rotations we need to perform and the direction in which we need to perform these rotations.
We can achieve this by keeping a variable, say 'ACTUAL_ROTATIONS', with its value initialized to zero. Whenever we are asked to perform a left rotation, ‘X’ number of times, we can simply subtract ‘X’ from 'ACTUAL_ROTATIONS'. If we are asked to perform a right rotation, ‘X’ number of times, then we can simply add ‘X’ to 'ACTUAL_ROTATIONS'.
Now, if the value of 'ACTUAL_ROTATIONS' is negative, this means that we need to perform left rotations, ‘X’ number of times, where ‘X’ is the value of 'ACTUAL_ROTATIONS'. And if ‘X’ is positive, we perform the right rotations, ‘X’ times.