LC2055 - Plates Between Candles

Description

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] = [lefti, righti] denotes the substring s[lefti…righti] (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 is 2, 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 ith 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:

ex-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 <= 105
s consists of ‘*‘ and ‘|’ characters.
1 <= queries.length <= 105
queries[i].length == 2
0 <= lefti <= righti < s.length

Solution

  • the position of the first candle to the right of the left endpoint
  • the position of the first candle to the left of the right endpoint
  • how many plates are between these two candles
  • Counting the nearest candle to the left and the nearest candle to the right of each point is a kind of simple dynamic programming. And finding the quantity of a certain type between two points is the standard prefix and application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# O(n) time | O(n) space
class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
length = len(s)
presum = [0]
lefts, rights = [-1] * length, [-1] * length
l,r = -1, -1

for i, v in enumerate(s):
if v == "*":
presum.append(presum[-1]+1)
else:
presum.append(presum[-1])
l = i
lefts[i] = l

for i, v in enumerate(s[::-1]):
if v == "|":
r = length - 1 - i
rights[length-1-i] = r

res = [0] * len(queries)
for i, query in enumerate(queries):
left = rights[query[0]]
right = lefts[query[1]]
if left >= 0 and right >= 0 and left < right:
res[i] = presum[right] - presum[left]
return res