The problem
Write a segment tree with lazy propagation (lesson 5). There are n values, all starting at 0. add(l, r, v) adds v to every value of a[l:r], and total(l, r) returns the sum of a[l:r]. Adds and totals come mixed, in any order.
t = RangeTree(8)
t.add(1, 7, 3)
t.total(0, 8) # 18
t.total(5, 7) # 6
t.add(0, 4, 1)
t.total(3, 5) # 7
Every range is half-open, as in Python slices: (l, r) means positions l up to but not including r, the same values as a[l:r].
v can be negative, and a range can be empty (then add does nothing and total is 0).
Limits
- Up to 200,000 values and 4,000 operations over wide ranges. Each operation should cost O(log n).
Builds on RNGQ-5 Lazy propagation.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Overlapping adds | Not run | |
| 3 | Single positions | Not run | |
| 4 | Negative and empty | Not run | |
| 5 | Not a power of two | Not run | |
| 6 | Many small checks | Not run | |
| 7 | 4,000 operations | Not run |