Plates Between Candles Problem
Description
LeetCode Problem 2055.
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.
You are also given a 0-indexed 2D integer array queries where queries[i] = [left_i, right_i] denotes the substring s[left_i...right_i] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.
- For example,
s = "||**||**|*", and a query[3, 8]denotes the substring"*||**|". The number of plates between candles in this substring is2, as each of the two plates has at least one candle in the substring to its left and right.
Return an integer array answer where answer[i] is the answer to the i^th query.
Example 1:

Input: s = "**|**|***|", queries = [[2,5],[5,9]]
Output: [2,3]
Explanation:
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
Example 2:

Input: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
Output: [9,0,0,0,0]
Explanation:
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.
Constraints:
3 <= s.length <= 10^5sconsists of'*'and'|'characters.1 <= queries.length <= 10^5queries[i].length == 20 <= left_i <= right_i < s.length
Solution
Approach: Prefix Sum + Nearest Candle
Only plates between the first and last candle inside the query range count, so for a query [l, r] we need the nearest candle at or after l and the nearest candle at or before r.
Precompute three arrays in one pass each: presum[i], the number of plates among the first i characters; left[i], the index of the closest candle at or before i; and right[i], the index of the closest candle at or after i (-1 if none). For a query take i = right[l] and j = left[r]. If both exist and i < j, the answer is presum[j] - presum[i + 1]; otherwise it is 0.
Complexity: time O(n + q), space O(n), where q is the number of queries.
class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
n = len(s)
presum = [0] * (n + 1)
for i, c in enumerate(s):
presum[i + 1] = presum[i] + (c == '*')
left, right = [0] * n, [0] * n
l = r = -1
for i, c in enumerate(s):
if c == '|':
l = i
left[i] = l
for i in range(n - 1, -1, -1):
if s[i] == '|':
r = i
right[i] = r
ans = [0] * len(queries)
for k, (l, r) in enumerate(queries):
i, j = right[l], left[r]
if i >= 0 and j >= 0 and i < j:
ans[k] = presum[j] - presum[i + 1]
return ans