Ula | OA | Count of Alphabets (Unsolved Question)
344

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 i
  • S ch K - Find smallest index i s.t. there are exactly K reps of character ch in range 1 to i

Input Format:

N Q
Str
... Q lines: L ch K or S ch K

Output Format: Q results

Test Cases

{
	input: {N: 6, Q: 2, Str: 'abaaba', queries: ['L a 1', 'S a 3']},
	output: [2, 4],
},

My Solution (Failed Half of Hidden Cases)

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
}
Comments (1)