RNGQ-P1

Adds, then sums

Practice 1 of 6Range queries7 tests

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

  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
2No addsNot run
3Whole listNot run
4Empty rangesNot run
5One cellNot run
6Negative valuesNot run
7100,000 adds and questionsNot run