
1. L ch K: Tell the largest index IDX for which there are exactly K repetitions of character ch between indices 1 to IDX.
2. S ch K: Tell the smallest index IDX for which there are exactly K repetitions of character ch between indices 1 to IDX.
If the given ‘ARR’ is [a,b,d,b,e] and the query is S b 2. Then the answer will be 4 as 4 is the smallest index for which 2 repetitions of ’b’ exist between 1 to 4.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains two integers, 'N’ and ‘Q’, denoting the number of letters and queries, respectively.
The second line contains the list of letters ‘ARR’.
The third line contains ‘TYPE’ array where TYPE[i] denotes the type of ith query.
The fourth line contains ‘LETTER’ array where LETTER[i] denotes the letter considered for ith query.
The fifth line contains ‘VALUE’ array where VALUE[i] denotes the number of repetitions for ith query.
For each test case, print a list of ‘Q’ values where ith value is the answer of ith query.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N,Q <= 10^4.
Time limit: 1 sec
In this approach, we will iterate through the list for each query, count the frequency of the respective character, find the required index according to the type of query asked, and store the answers of each query in an array ‘ANS’.
At last, we will return the ‘ANS’ array.
If we try to observe the answer, we found a pattern that :
For Type ‘S’, the answer is the index of the VALUE[i]’th repetition of ‘LETTER[i]’ as it is the smallest index so that exactly ‘VALUE[i]’ repetition of ‘LETTER’[i] occurs between 1 to this index.
For Type ‘L’, the answer will be one less than the index of the (VALUE[i] +1)th occurrence of ‘LETTER[i]’. Because if we include that index, we will have more extra repetition in the range. So, the largest index possible is one less than the index of the (VALUE[i] +1)th occurrence of ‘LETTER[i]’.
To find the indices of each character quickly, we will store the indices of all occurrences of each character in a 2-D array, ‘INDICES’. INDICES[i][j] will denotes index of j+1th occurrence of (i+1)th character. So, with the help of his 2-D array, we can answer each query in constant time.