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.

Examples

Example 1

1
2
3
4
5
6

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

1
2
3
4
5
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^5
  • s consists of '*' and '|' characters.
  • 1 <= queries.length <= 10^5
  • queries[i].length == 2
  • 0 <= lefti <= righti < s.length

Solution

Method 1 - Prefix Sum with Nearest Candles

Intuition

For each query, we need to efficiently count the number of plates ('*') that are between two candles (’|’) within the substring. Since both s and queries can be large, a brute-force approach is too slow. We can use a prefix sum array prefix (where prefix[i] counts plates up to index i-1) and precompute the nearest candle indices to the left and right for each position as arrays left and right, allowing O(1) answers per query after O(n) preprocessing.

Approach

  1. Precompute a prefix-sum array prefix of plates where prefix[i] = number of '*' in s[0..i-1].
  2. For each position i, precompute left[i] = index of the nearest candle at or before i (or -1 if none) and right[i] = index of the nearest candle at or after i (or n if none).
  3. For each query [l, r]:
    • Let left_candle = right[l] (first candle at or after l).
    • Let right_candle = left[r] (last candle at or before r).
    • If left_candle < right_candle, answer is prefix[right_candle] - prefix[left_candle]; otherwise answer is 0.

Complexity

  • ⏰ Time complexity: O(n + q), where n is the length of s and q is the number of queries.
  • 🧺 Space complexity: O(n) for prefix sums and nearest candle arrays.

Code

 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
29
30
31
#include <vector>
#include <string>
using namespace std;

class Solution {
public:
    vector<int> platesBetweenCandles(string s, vector<vector<int>>& queries) {
        int n = s.size();
        vector<int> prefix(n + 1, 0);
        for (int i = 0; i < n; ++i)
            prefix[i + 1] = prefix[i] + (s[i] == '*' ? 1 : 0);
        vector<int> left(n, -1), right(n, n);
        for (int i = 0, last = -1; i < n; ++i) {
            if (s[i] == '|') last = i;
            left[i] = last;
        }
        for (int i = n - 1, last = n; i >= 0; --i) {
            if (s[i] == '|') last = i;
            right[i] = last;
        }
        vector<int> res;
        for (auto& q : queries) {
            int l = right[q[0]], r = left[q[1]];
            if (l < r)
                res.push_back(prefix[r] - prefix[l]);
            else
                res.push_back(0);
        }
        return res;
    }
};
 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
29
30
31
32
33
34
35
36
func platesBetweenCandles(s string, queries [][]int) []int {
    n := len(s)
    prefix := make([]int, n+1)
    for i := 0; i < n; i++ {
        prefix[i+1] = prefix[i]
        if s[i] == '*' {
            prefix[i+1]++
        }
    }
    left := make([]int, n)
    right := make([]int, n)
    last := -1
    for i := 0; i < n; i++ {
        if s[i] == '|' {
            last = i
        }
        left[i] = last
    }
    last = n
    for i := n - 1; i >= 0; i-- {
        if s[i] == '|' {
            last = i
        }
        right[i] = last
    }
    res := make([]int, len(queries))
    for i, q := range queries {
        l, r := right[q[0]], left[q[1]]
        if l < r {
            res[i] = prefix[r] - prefix[l]
        } else {
            res[i] = 0
        }
    }
    return res
}
 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
29
import java.util.*;
class Solution {
    public int[] platesBetweenCandles(String s, int[][] queries) {
        int n = s.length();
        int[] prefix = new int[n + 1];
        for (int i = 0; i < n; i++)
            prefix[i + 1] = prefix[i] + (s.charAt(i) == '*' ? 1 : 0);
        int[] left = new int[n], right = new int[n];
        int last = -1;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '|') last = i;
            left[i] = last;
        }
        last = n;
        for (int i = n - 1; i >= 0; i--) {
            if (s.charAt(i) == '|') last = i;
            right[i] = last;
        }
        int[] res = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int l = right[queries[i][0]], r = left[queries[i][1]];
            if (l < r)
                res[i] = prefix[r] - prefix[l];
            else
                res[i] = 0;
        }
        return res;
    }
}
 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
class Solution {
    fun platesBetweenCandles(s: String, queries: Array<IntArray>): IntArray {
        val n = s.length
        val prefix = IntArray(n + 1)
        for (i in 0 until n)
            prefix[i + 1] = prefix[i] + if (s[i] == '*') 1 else 0
        val left = IntArray(n)
        val right = IntArray(n)
        var last = -1
        for (i in 0 until n) {
            if (s[i] == '|') last = i
            left[i] = last
        }
        last = n
        for (i in n - 1 downTo 0) {
            if (s[i] == '|') last = i
            right[i] = last
        }
        return queries.map {
            val l = right[it[0]]
            val r = left[it[1]]
            if (l < r) prefix[r] - prefix[l] else 0
        }.toIntArray()
    }
}
 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
class Solution:
    def platesBetweenCandles(self, s: str, queries: list[list[int]]) -> list[int]:
        n = len(s)
        prefix = [0] * (n + 1)
        for i in range(n):
            prefix[i + 1] = prefix[i] + (s[i] == '*')
        left = [-1] * n
        right = [n] * n
        last = -1
        for i in range(n):
            if s[i] == '|':
                last = i
            left[i] = last
        last = n
        for i in range(n - 1, -1, -1):
            if s[i] == '|':
                last = i
            right[i] = last
        res = []
        for l, r in queries:
            l_candle = right[l]
            r_candle = left[r]
            if l_candle < r_candle:
                res.append(prefix[r_candle] - prefix[l_candle])
            else:
                res.append(0)
        return res
 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
29
impl Solution {
    pub fn plates_between_candles(s: String, queries: Vec<Vec<i32>>) -> Vec<i32> {
        let n = s.len();
        let s = s.as_bytes();
        let mut prefix = vec![0; n + 1];
        for i in 0..n {
            prefix[i + 1] = prefix[i] + if s[i] == b'*' { 1 } else { 0 };
        }
        let mut left = vec![-1; n];
        let mut right = vec![n as i32; n];
        let mut last = -1;
        for i in 0..n {
            if s[i] == b'|' { last = i as i32; }
            left[i] = last;
        }
        last = n as i32;
        for i in (0..n).rev() {
            if s[i] == b'|' { last = i as i32; }
            right[i] = last;
        }
        queries.iter().map(|q| {
            let l = right[q[0] as usize];
            let r = left[q[1] as usize];
            if l < r {
                prefix[r as usize] - prefix[l as usize]
            } else { 0 }
        }).collect()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function platesBetweenCandles(s: string, queries: number[][]): number[] {
    const n = s.length;
    const prefix = new Array(n + 1).fill(0);
    for (let i = 0; i < n; i++)
        prefix[i + 1] = prefix[i] + (s[i] === '*' ? 1 : 0);
    const left = new Array(n).fill(-1);
    const right = new Array(n).fill(n);
    let last = -1;
    for (let i = 0; i < n; i++) {
        if (s[i] === '|') last = i;
        left[i] = last;
    }
    last = n;
    for (let i = n - 1; i >= 0; i--) {
        if (s[i] === '|') last = i;
        right[i] = last;
    }
    return queries.map(([l, r]) => {
        const lCandle = right[l], rCandle = left[r];
        return lCandle < rCandle ? prefix[rCandle] - prefix[lCandle] : 0;
    });
}