-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplatesBetweenCandles.ts
56 lines (42 loc) · 1.28 KB
/
platesBetweenCandles.ts
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// <Prefix Sum>
// Time: O(n)
// Space: O(n)
function platesBetweenCandles(s: string, queries: [number, number][]): number[] {
const n = s.length
let platesLeft = 0
let candleLeft = -1
let candleRight = -1
// 1. prefix sum
const prefixSum: number[] = []
// 2. memorize the nearest index of the candles
const nearestCandleOnTheLeft: number[] = []
const nearestCandleOnTheRight: number[] = []
for (let i = 0; i < n; ++i) {
if (s[i] === '|') {
candleLeft = i
} else {
++platesLeft
}
prefixSum.push(platesLeft)
nearestCandleOnTheLeft.push(candleLeft)
if (s[n - i - 1] === '|') {
candleRight = n - i - 1
}
nearestCandleOnTheRight.push(candleRight)
}
nearestCandleOnTheRight.reverse()
const ans: number[] = []
// 3. traverse the queries
for (const query of queries) {
const [left, right] = query
const l = s[left] === '|' ? left : nearestCandleOnTheRight[left]
const r = s[right] === '|' ? right : nearestCandleOnTheLeft[right]
if (l < 0 || r < 0 || r < l) {
ans.push(0)
} else {
ans.push(prefixSum[r] - prefixSum[l])
}
}
return ans
}
export { platesBetweenCandles }