RNGQ-P5

Add to a range, sum a range

Practice 5 of 6Range queries7 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

7 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Overlapping addsNot run
3Single positionsNot run
4Negative and emptyNot run
5Not a power of twoNot run
6Many small checksNot run
74,000 operationsNot run