Plates Between Candles - Problem

Imagine you're at an elegant dinner party where a long dining table is decorated with alternating plates and candles. You're given a string s where '*' represents a plate and '|' represents a candle.

Your task is to answer multiple queries efficiently. For each query [left, right], you need to count how many plates are properly positioned between candles within that substring range.

What makes a plate "between candles"?
A plate is considered between candles if there's at least one candle to its left AND at least one candle to its right within the given substring.

Example: For s = "||**||**|*" and query [3, 8], the substring is "*||**|". The two plates marked with ** in the middle are between candles, so the answer is 2.

Goal: Return an array where each element is the answer to the corresponding query.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "**|**|***|", queries = [[2,5],[5,9]]
โ€บ Output: [2, 3]
๐Ÿ’ก Note: Query [2,5]: substring "**|***" has leftmost candle at index 2 and rightmost at index 5, with 2 plates between them. Query [5,9]: substring "|***|" has 3 plates between candles at indices 5 and 9.
example_2.py โ€” Complex Case
$ Input: s = "||**||**|*", queries = [[3,8]]
โ€บ Output: [2]
๐Ÿ’ก Note: Query [3,8]: substring "*||**|" has first candle at index 4, last candle at index 8. Between these candles are 2 plates (the ** part).
example_3.py โ€” Edge Case
$ Input: s = "***", queries = [[0,2]]
โ€บ Output: [0]
๐Ÿ’ก Note: No candles in the substring, so no plates can be between candles. Result is 0.

Constraints

  • 3 โ‰ค s.length โ‰ค 105
  • s consists of '*' and '|' characters only
  • 1 โ‰ค queries.length โ‰ค 105
  • queries[i].length == 2
  • 0 โ‰ค lefti โ‰ค righti < s.length

Visualization

Tap to expand
Elegant Dinner Table๐Ÿ•ฏ๏ธ๐Ÿฝ๏ธ๐Ÿฝ๏ธ๐Ÿ•ฏ๏ธIlluminated ZonePlates between candles are properly illuminated!
Understanding the Visualization
1
Setup Phase
Create a map of candle positions and plate counts for quick reference
2
Query Processing
When guests ask about their section, instantly find the boundary candles
3
Count Calculation
Use the precomputed data to calculate illuminated plates in constant time
Key Takeaway
๐ŸŽฏ Key Insight: By preprocessing candle positions and plate counts, we transform a potentially expensive O(n) query operation into an instant O(1) lookup, making our dinner party management incredibly efficient!
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 25
68.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen