#2055

Plates Between Candles

Medium
ArrayStringBinary SearchPrefix SumPrefix SumBinary Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q log m)
Space
O(1)
O(n + m)
💡

Intuition

Time O(n + q log m)Space O(n + m)

By using prefix sums and pre-computed candle positions, we can efficiently answer each query in constant time after an initial linear pass through the string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array to store the prefix sum of plates up to each index.
  2. 2Step 2: Create an array to store the positions of all candles in the string.
  3. 3Step 3: For each query, use binary search to find the nearest candles to the left and right of the given indices.
  4. 4Step 4: Calculate the number of plates between these two candle indices using the prefix sum array.
solution.py21 lines
1def platesBetweenCandles(s, queries):
2    n = len(s)
3    prefix = [0] * n
4    candle_positions = []
5    count = 0
6    for i in range(n):
7        if s[i] == '*':
8            count += 1
9        prefix[i] = count
10        if s[i] == '|':
11            candle_positions.append(i)
12    results = []
13    for left, right in queries:
14        left_candle = bisect.bisect_right(candle_positions, left) - 1
15        right_candle = bisect.bisect_left(candle_positions, right)
16        if left_candle >= 0 and right_candle < len(candle_positions) and candle_positions[left_candle] < candle_positions[right_candle]:
17            plates_count = prefix[candle_positions[right_candle] - 1] - prefix[candle_positions[left_candle]]
18            results.append(plates_count)
19        else:
20            results.append(0)
21    return results

Complexity note: The initial pass through the string is O(n) to create the prefix sums and candle positions, while each query can be answered in O(log m) due to binary search, where m is the number of candles.

  • 1Using prefix sums allows for quick calculations of counts within ranges.
  • 2Binary search helps efficiently locate the nearest candles for any given query.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.