Given string of size N
Q queries of two possible types:
L ch K - Find largest index i s.t there are exactly K reps of character ch in range 1 to iS ch K - Find smallest index i s.t. there are exactly K reps of character ch in range 1 to iInput Format:
N Q
Str
... Q lines: L ch K or S ch KOutput Format: Q results
{
input: {N: 6, Q: 2, Str: 'abaaba', queries: ['L a 1', 'S a 3']},
output: [2, 4],
},function countL(N, str, K, ch) {
let index = 0
let count = 0
while (N--) {
const char = str[index]
if (char === ch) {
if (count < K) {
count++
} else {
return index
}
}
index++
}
}
function countS(N, str, K, ch) {
let index = 0
let count = 0
while (N-- && count < K) {
const char = str[index]
if (char === ch) {
count++
}
index++
}
return index
}
function countOfAlphabets(N, Q, Str, queries) {
let index = 0
const result = []
while (index < Q) {
const query = queries[index++]
const [op, ch, K] = query.split(' ')
switch (op) {
case 'L': {
result.push(countL(N, Str, K, ch))
break
}
case 'S': {
result.push(countS(N, Str, K, ch))
break
}
}
}
return result
}