Problem Description
Given a string s consisting of plates ('*') and candles ('|'), and a list of queries where each query specifies a substring by its start and end indices, determine for each query the number of plates positioned between the leftmost and rightmost candle within that substring. A plate is "between candles" if there is at least one candle to its left and one to its right in the substring.
Key Insights
- Precompute a prefix sum array for the count of plates.
- Use two auxiliary arrays:
- One to track the nearest candle on the left of every index.
- One to track the nearest candle on the right.
- For a query, use the right-nearest candle from the left boundary as the effective start and the left-nearest candle from the right boundary as the effective end.
- The answer for a query is the difference between the prefix sum at the effective end and effective start, if valid.
Space and Time Complexity
Time Complexity: O(n + q) where n is the length of s and q is the number of queries. Space Complexity: O(n)
Solution
We start by computing a prefix sum array that counts the number of plates up to each position. Then, we precompute two arrays: one that stores for each index the nearest candle seen from the left, and another for the nearest candle from the right. For each query, we locate the first candle at or after the left index (using the right-candle array) and the last candle at or before the right index (using the left-candle array). If these indices are valid and the first candle comes before the last, the number of plates is the difference in their respective prefix sums. Otherwise, the answer is 0.