Plates Between Candles - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "**|**|***|", queries = [[2,5],[5,9]]
Output: [2,3]
💡 Note: Query [2,5]: substring is "|**|", plates at indices 3,4 are between candles at 2,5. Query [5,9]: substring is "|***|", plates at indices 6,7,8 are between candles at 5,9.
Example 2 — No Candles
$ Input: s = "***", queries = [[0,2]]
Output: [0]
💡 Note: Query [0,2]: substring is "***", no candles exist so no plates can be between candles.
Example 3 — Single Candle
$ Input: s = "|**|", queries = [[0,3]]
Output: [2]
💡 Note: Query [0,3]: substring is "|**|", plates at indices 1,2 are between candles at 0,3.

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
Plates Between Candles Problem OverviewString: "||**||**|*"||**||**|*0123456789Query [3,8]: substring "*||**|"Query RangeLRLeft candleRight candleValid platesbetween candlesOutput: [2] (2 plates between candles)
Understanding the Visualization
1
Input
String of plates (*) and candles (|) with query ranges
2
Process
For each query, find plates between leftmost and rightmost candles
3
Output
Array of plate counts for each query
Key Takeaway
🎯 Key Insight: Only plates between the first and last candle in a range count as 'between candles'
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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