The problem
Start with a list of n zeros. Apply every add in adds: (l, r, v) adds v to each of a[l:r]. Then return a list with the answer to each query (l, r): the total of a[l:r].
after_adds(7, [(1, 4, 2), (3, 7, 5), (0, 2, 1)],
[(0, 7), (2, 5), (3, 4), (6, 7)])
# the list becomes [1, 3, 2, 7, 5, 5, 5]
# answers: [28, 14, 7, 5]
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].
Values v can be negative, and a range can be empty (l equal to r).
Limits
- Up to 200,000 positions, 100,000 adds and 100,000 queries. Each add and each query must cost O(1), plus O(n) once.
Builds on RNGQ-1 Prefix sums revisited.
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 | No adds | Not run | |
| 3 | Whole list | Not run | |
| 4 | Empty ranges | Not run | |
| 5 | One cell | Not run | |
| 6 | Negative values | Not run | |
| 7 | 100,000 adds and questions | Not run |