Range Sum Query 2D - Mutable

Hard · Matrix · Array · Design · Binary Indexed Tree · Segment Tree · Matrix

Problem

Design a class over a 2D integer matrix that supports point updates and rectangle-sum queries, called in any order.

A plain prefix-sum table makes each update expensive, and summing cells makes each query expensive. Aim for sub-linear time for both operations.

The tests call the class through a list of operation names and a list of their arguments; the expected output lists each call's return value, None for the constructor and update.

Examples

Input: ops = ["NumMatrix","sumRegion","update","sumRegion"], args = [[[[2,0,1],[4,3,5],[1,6,2]]],[0,0,1,1],[1,1,10],[0,0,1,1]]
Output: [None, 9, None, 16]

The top-left 2 × 2 block sums to 2 + 0 + 4 + 3 = 9. Setting the 3 to 10 raises it by 7, to 16.

Input: ops = ["NumMatrix","update","update","sumRegion","sumRegion"], args = [[[[1,1],[1,1]]],[0,0,5],[1,1,-2],[0,0,1,1],[0,0,0,1]]
Output: [None, None, None, 5, 6]

After the updates the matrix is [[5,1],[1,-2]]: its total is 5 and its top row sums to 6.

Constraints

Approaches

Follow-up

What if updates add to a whole rectangle and queries read single cells? Store a difference grid in the same tree: the use cases cover that and a toggle-and-count grid.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…