RNGQ-P6

Blocks: add and largest

Practice 6 of 6Range queries7 tests

The problem

Use square-root decomposition (lesson 6) for two operations on a list: add(l, r, v) adds v to every value of a[l:r], and largest(l, r) returns the largest value of a[l:r].

b = Blocks([5, 2, 7, 4, 6, 1, 8, 3])
b.largest(0, 8)     # 8
b.add(1, 7, 3)      # [5, 5, 10, 7, 9, 4, 11, 3]
b.largest(3, 6)     # 9

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].

Ranges for largest are never empty; an empty range for add changes nothing. A lazy segment tree also solves this, and passes the tests.

Limits

  • Up to 160,000 values and 2,000 operations over wide ranges. Each operation should cost about O(√n); looping over the whole range is too slow.

Builds on RNGQ-6 Square-root decomposition.

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
2Inside one blockNot run
3Whole blocksNot run
4Values go downNot run
5Odd lengthNot run
6Many small checksNot run
7160,000 valuesNot run