You are playing a dominoes game with your friends in which you have ‘N’ dominoes placed vertically upright. At the start of the game, you simultaneously pushed some of the dominoes either to the left or to the right. After each second, each domino falling to the right pushes the adjacent domino on the right. Similarly, the dominoes falling to the left pushes the adjacent domino on the left. When a vertical domino has dominoes falling to it from both sides, it stays as it is due to the balance of the forces. You are given a string ‘S’ of length ‘N’, representing the states of the dominoes where ‘L’ represents a domino falling in the left direction, ‘R’ represents domino falling right direction, and ‘.’ represents domino has not been pushed initially. Print the final state of the dominoes.
Note:A falling domino exerts no additional force to a falling domino or an already fallen domino.
For example:
Let ‘S' be: “R.L”
The second domino is pushed from both directions, therefore remains still.
So the final state becomes “R.L”.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains a string ‘S’, representing the initial state of the dominoes.
Output Format :
For each test case, print a single string representing the final state of the dominoes.
Print output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |S| <= 10^6
S only contains {‘L’, ‘R’, ‘.’}
Time Limit: 1 sec
2
R.L
R..
R.L
RRR
For test case 1:
The second domino is pushed from both directions, therefore remains still.
So the final state becomes “R.L”.
For test case 2:
The first domino exerts a force on the second domino, which exerts a force on the third domino.
So the final state becomes “RRR”.
2
R.LLL....RR
.L.R...LR..L..
R.LLL....RR
LL.RR.LLRRLL..
Try to find the direction of the dominoes adjacent to the non-falling dominoes.
For each group of non-falling dominoes, we will have two falling dominoes at the end of each group. There are four cases we need to consider:
Here is the algorithm :
O(N), where ‘N’ is the size of the string.
We iterate the string once to find the falling dominoes’ index and position, which takes O(N) time. We then run a loop again to update the direction of the dominoes, which can take up to O(N) time. Therefore, the overall time complexity will be O(N).
O(N), where ‘N’ is the size of the string.
We use two extra arrays, ‘IDX’ and ‘POS’ to store the indexes and the position of the falling dominoes. Therefore, the overall space complexity will be O(N).