You are given a string ‘S’, containing all capital letters from ‘A’ - ‘Z’. Your task is to count the number of times the “ROR” occurs as a subsequence in the string ‘S’.
Note:Since the answer can be very large print the answer modulo 10 ^ 9 + 7.
For example
Given:
‘S’ = OORROR.
The answer will be two since 2 “ROR” can be formed from the index (2,4,5), and (3,4,5) (0-based indexing).
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ line contains a string ‘S,’ containing capital letters.
Output Format :
For each test case, You are supposed to return an integer that denotes the total number of times “ROR” occurs as a subsequence.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^4
Time Limit: 1sec.
2
OORROR
OOROR
2
1
In the first test case, The answer will be 2, since 2 “ROR” can be formed from the index (2,4,5), and (3,4,5) (0-based indexing).
In the second test case, The answer will be 1, since 1 “ROR” can be formed from the index (2,3,4) (0-based indexing).
2
ROOROO
RRROO
2
0
Can we naively match the strings?
The idea is to use recursion and match “ROR” in our string ‘S’. If we match at some index, then we recur on the rest of the substring of “ROR” and ‘S’, but at the same time also recur for the same position of “ROR” in ‘S’.
The steps are as follows:
O((2 ^ N)), Where ‘N’ is the length of ‘S’.
Since we are using recursion and for each case we have two calls, therefore the overall time complexity will be O(2 ^ N).
O(N), Where ‘N’ is the length of ‘S’.
Since we are using recursion, a call stack up to height ‘N’ would be made. Hence the overall space complexity will be O(N).