Monitoring~30 min2s · 256 MBtarget O((n + q) log n) time, O(n) spaceclassic twin: lc-307fenwick-tree
A monitoring service stores the number of errors for each minute of a day. Late log lines arrive and correct old minutes, and engineers keep asking for the total errors between two minutes.
The day has up to 100,000 minutes, and there can be 100,000 corrections and questions. Answer every question with the counts as they are at that moment.
Write run_counters(counts, ops).
counts[i] is the number of errors in minute i. It starts as given.[kind, a, b].
[0, a, b] sets the count of minute a to b.[1, a, b] adds b to the count of minute a. b may be negative, and a count never goes below 0.[2, a, b] asks for the total of the counts of minutes a to b, both included, with a <= b.Input: counts = [2, 5, 3, 7, 1, 4], ops = [[2, 1, 3], [0, 2, 10], [2, 1, 3], [1, 0, -1], [2, 0, 5]]
Output: [15, 22, 28]A Fenwick tree keeps slot i as the total of the minutes that end at minute i, as many as the lowest set bit of i. For these counts the slots 1 to 6 are [2, 7, 3, 17, 1, 5].
| Step | What happens | Slots changed or read |
|---|---|---|
| [2] | Minutes 1 to 3: prefix of 4 is slot 4 = 17, minus prefix of 1 = 2 | 15 |
| [3] | Set minute 2 to 10: a change of 7 goes to slots 3 and 4 | slot 3 = 10, slot 4 = 24 |
| [2] | Minutes 1 to 3 again: 24 - 2 | 22 |
| [3] | Add -1 to minute 0: slots 1, 2 and 4 each drop by 1 | [1, 6, 10, 23, 1, 5] |
| [2] | Minutes 0 to 5: slot 6 + slot 4 = 5 + 23 | 28 |
Input: counts = [9], ops = [[2, 0, 0], [1, 0, 6], [2, 0, 0]]
Output: [9, 15]One minute: the total of a single minute is its count.
Input: counts = [1, 1, 1], ops = [[0, 0, 4], [0, 0, 4], [2, 0, 2]]
Output: [6]Setting minute 0 to 4 twice leaves it at 4, not 8. The total is 4 + 1 + 1.
1 ≤ len(counts) ≤ 100,000 and 0 ≤ counts[i] ≤ 10,0001 ≤ len(ops) ≤ 100,000, and every operation has three entries0 to len(counts) - 1, and a set value is between 0 and 10,000-10,000 to 10,000, and a count never goes below 0Adding up a range one minute at a time costs up to 100,000 steps, and there can be 100,000 questions. That is 10 billion steps.
Rebuilding all prefix totals after each change also costs 100,000 steps. We need both a change and a question to cost about log n, which is 17 steps for 100,000 minutes.