Payments app~25 min2s · 256 MBtarget O((n + q) log n) time, O(n) spaceclassic twin: lc-307fenwick-tree
You work on a payments app. A ledger holds the takings of each hour of a trading day, in whole units. Late corrections arrive and replace the figure for one hour.
Between corrections, the finance team asks for the total takings of a run of hours. Your team lead asks: "Can we answer each question straight away?" A day's ledger can hold 100,000 hours and 100,000 operations.
Write ledger_sums(takings, ops).
takings[i] is the takings of hour i, counting from 0.ops is a list of operations in time order. Each operation is [kind, a, b].[0, a, b] is a correction: the takings of hour a become b.[1, a, b] is a question: what is the total takings of hours a to b, both included? Here a ≤ b.Input: takings = [5, 3, 8, 6, 2], ops = [[1, 0, 4], [0, 2, 1], [1, 1, 3], [0, 0, 10], [1, 0, 2]]
Output: [24, 10, 14]Apply the operations in order. After each correction the ledger changes, so the same hours can give a different total later.
| Operation | Takings afterwards | Answer |
|---|---|---|
| Total of hours 0 to 4 | [5, 3, 8, 6, 2] | 24 |
| Set hour 2 to 1 | [5, 3, 1, 6, 2] | none |
| Total of hours 1 to 3 | [5, 3, 1, 6, 2] | 10 |
| Set hour 0 to 10 | [10, 3, 1, 6, 2] | none |
| Total of hours 0 to 2 | [10, 3, 1, 6, 2] | 14 |
The answers are the figures in the last column: 24, 10, 14.
Input: takings = [7], ops = [[1, 0, 0], [0, 0, 0], [1, 0, 0]]
Output: [7, 0]One hour. A correction to the same value changes nothing, so both answers are 7.
Input: takings = [1, 1, 1, 1], ops = [[1, 1, 2], [0, 1, 4], [1, 0, 3]]
Output: [2, 7]Hours 1 and 2 hold 2 in total. After the correction the four hours hold 1, 4, 1 and 1, which is 7.
1 ≤ len(takings) ≤ 100,0000 ≤ takings[i] ≤ 1,000,0001 ≤ len(ops) ≤ 100,0000 ≤ a < len(takings). A correction has 0 ≤ b ≤ 1,000,000. A question has a ≤ b < len(takings).Adding up the hours of every question can read 100,000 hours each time. For 100,000 questions that is up to 10 billion reads, too slow for a 2-second limit. Keeping a running prefix total does not help either, because one correction would change up to 100,000 prefix totals. You need a structure where both a correction and a question touch only about 17 values.