AlgoInsight

DSA problem

Range Sum Query 2D - Mutable

HardBinary Indexed Tree / Segment TreePattern: Binary Indexed Tree / Segment Treetop600GoogleAmazonMicrosoftBloomberg

Given a 2D matrix matrix, handle queries that update a single cell and queries that return the sum of all elements inside an axis-aligned rectangle. Implement the NumMatrix class with update(row, col, val) and sumRegion(row1, col1, row2, col2) where the rectangle is inclusive on both corners.

The static (immutable) version of this problem precomputes a 2D prefix-sum table once for O(1) queries. That breaks down here because each update would force an O(rows * cols) refresh of the table — far too slow when many updates are interleaved with queries.

The natural generalization is a 2D Binary Indexed Tree. The key observation: a 1D Fenwick tree supports prefix sums; nesting one Fenwick tree per row index inside another Fenwick tree along the column axis yields a structure where any rectangle prefix sum from (0, 0) to (r, c) is computed in O(log m * log n). The bit-manipulation walks are identical to 1D — just performed independently on each axis.

update(r, c, val) translates to a delta point-add on the 2D BIT. sumRegion(r1, c1, r2, c2) is built by inclusion-exclusion of four prefix rectangles: P(r2, c2) - P(r1 - 1, c2) - P(r2, c1 - 1) + P(r1 - 1, c1 - 1). Per call, both run in O(log m * log n) using O(m * n) extra space.

Examples

Example 1
Input: ["NumMatrix","sumRegion","update","sumRegion"] [[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[3,2,2],[2,1,4,3]]
Output: [null,8,null,10]
Explanation: sumRegion(2,1,4,3) over the initial matrix is 8. After update(3,2,2), changing matrix[3][2] from 0 to 2 adds 2 to the same rectangle, giving 10.
Example 2
Input: ["NumMatrix","sumRegion","update","update","sumRegion"] [[[[1,2],[3,4]]],[0,0,1,1],[0,0,5],[1,1,0],[0,0,1,1]]
Output: [null,10,null,null,10]
Explanation: Initial sum 1+2+3+4 = 10. After update(0,0,5) and update(1,1,0) the matrix is [[5,2],[3,0]] with sum 10.
Example 3
Input: ["NumMatrix","sumRegion"] [[[[5]]],[0,0,0,0]]
Output: [null,5]
Explanation: A single-cell matrix; the only rectangle is the cell itself.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-indexed-treesegment-treedesignmatrix2d-bit

Browse all DSA problems