Given a 2D matrix matrix, handle multiple queries of the following types:
Update the value of a cell in matrix.
Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner(row1, col1) and lower right corner(row2, col2).
Implement the NumMatrix class:
NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
void update(int row, int col, int val)Updates the value of matrix[row][col] to be val.
int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner(row1, col1) and lower right corner(row2, col2).
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
NumMatrix numMatrix = new NumMatrix([[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]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e. sum of the left red rectangle)
numMatrix.update(3, 2, 2); // matrix changes from left image to right image
numMatrix.sumRegion(2, 1, 4, 3); // return 10 (i.e. sum of the right red rectangle)
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-1000 <= matrix[i][j] <= 1000
0 <= row < m
0 <= col < n
-1000 <= val <= 1000
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
At most 5000 calls will be made to sumRegion and update.
Solutions
Solution 1
Thinking
The matrix needs both point updates and sub-rectangle sums. Scanning a rectangle per query, or rebuilding a 2D prefix after every write, cannot keep both cheap.
The code builds one Fenwick tree per row: a row range is a prefix difference, then those rows in \([row1,row2]\) are added. An update touches only that row. With a modest number of rows this is simpler than a true 2D Fenwick tree.
classBinaryIndexedTree:def__init__(self,n):self.n=nself.c=[0]*(n+1)@staticmethoddeflowbit(x):returnx&-xdefupdate(self,x,delta):whilex<=self.n:self.c[x]+=deltax+=BinaryIndexedTree.lowbit(x)defquery(self,x):s=0whilex>0:s+=self.c[x]x-=BinaryIndexedTree.lowbit(x)returnsclassNumMatrix:def__init__(self,matrix:List[List[int]]):self.trees=[]n=len(matrix[0])forrowinmatrix:tree=BinaryIndexedTree(n)forj,vinenumerate(row):tree.update(j+1,v)self.trees.append(tree)defupdate(self,row:int,col:int,val:int)->None:tree=self.trees[row]prev=tree.query(col+1)-tree.query(col)tree.update(col+1,val-prev)defsumRegion(self,row1:int,col1:int,row2:int,col2:int)->int:returnsum(tree.query(col2+1)-tree.query(col1)fortreeinself.trees[row1:row2+1])# Your NumMatrix object will be instantiated and called as such:# obj = NumMatrix(matrix)# obj.update(row,col,val)# param_2 = obj.sumRegion(row1,col1,row2,col2)
classBinaryIndexedTree{privateintn;privateint[]c;publicBinaryIndexedTree(intn){this.n=n;c=newint[n+1];}publicvoidupdate(intx,intdelta){while(x<=n){c[x]+=delta;x+=lowbit(x);}}publicintquery(intx){ints=0;while(x>0){s+=c[x];x-=lowbit(x);}returns;}publicstaticintlowbit(intx){returnx&-x;}}classNumMatrix{privateBinaryIndexedTree[]trees;publicNumMatrix(int[][]matrix){intm=matrix.length;intn=matrix[0].length;trees=newBinaryIndexedTree[m];for(inti=0;i<m;++i){BinaryIndexedTreetree=newBinaryIndexedTree(n);for(intj=0;j<n;++j){tree.update(j+1,matrix[i][j]);}trees[i]=tree;}}publicvoidupdate(introw,intcol,intval){BinaryIndexedTreetree=trees[row];intprev=tree.query(col+1)-tree.query(col);tree.update(col+1,val-prev);}publicintsumRegion(introw1,intcol1,introw2,intcol2){ints=0;for(inti=row1;i<=row2;++i){BinaryIndexedTreetree=trees[i];s+=tree.query(col2+1)-tree.query(col1);}returns;}}/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * obj.update(row,col,val); * int param_2 = obj.sumRegion(row1,col1,row2,col2); */
classBinaryIndexedTree{public:intn;vector<int>c;BinaryIndexedTree(int_n):n(_n),c(_n+1){}voidupdate(intx,intdelta){while(x<=n){c[x]+=delta;x+=lowbit(x);}}intquery(intx){ints=0;while(x>0){s+=c[x];x-=lowbit(x);}returns;}intlowbit(intx){returnx&-x;}};classNumMatrix{public:vector<BinaryIndexedTree*>trees;NumMatrix(vector<vector<int>>&matrix){intm=matrix.size();intn=matrix[0].size();trees.resize(m);for(inti=0;i<m;++i){BinaryIndexedTree*tree=newBinaryIndexedTree(n);for(intj=0;j<n;++j)tree->update(j+1,matrix[i][j]);trees[i]=tree;}}voidupdate(introw,intcol,intval){BinaryIndexedTree*tree=trees[row];intprev=tree->query(col+1)-tree->query(col);tree->update(col+1,val-prev);}intsumRegion(introw1,intcol1,introw2,intcol2){ints=0;for(inti=row1;i<=row2;++i){BinaryIndexedTree*tree=trees[i];s+=tree->query(col2+1)-tree->query(col1);}returns;}};/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * obj->update(row,col,val); * int param_2 = obj->sumRegion(row1,col1,row2,col2); */
typeBinaryIndexedTreestruct{nintc[]int}funcnewBinaryIndexedTree(nint)*BinaryIndexedTree{c:=make([]int,n+1)return&BinaryIndexedTree{n,c}}func(this*BinaryIndexedTree)lowbit(xint)int{returnx&-x}func(this*BinaryIndexedTree)update(x,deltaint){forx<=this.n{this.c[x]+=deltax+=this.lowbit(x)}}func(this*BinaryIndexedTree)query(xint)int{s:=0forx>0{s+=this.c[x]x-=this.lowbit(x)}returns}typeNumMatrixstruct{trees[]*BinaryIndexedTree}funcConstructor(matrix[][]int)NumMatrix{n:=len(matrix[0])vartrees[]*BinaryIndexedTreefor_,row:=rangematrix{tree:=newBinaryIndexedTree(n)forj,v:=rangerow{tree.update(j+1,v)}trees=append(trees,tree)}returnNumMatrix{trees}}func(this*NumMatrix)Update(rowint,colint,valint){tree:=this.trees[row]prev:=tree.query(col+1)-tree.query(col)tree.update(col+1,val-prev)}func(this*NumMatrix)SumRegion(row1int,col1int,row2int,col2int)int{s:=0fori:=row1;i<=row2;i++{tree:=this.trees[i]s+=tree.query(col2+1)-tree.query(col1)}returns}/** * Your NumMatrix object will be instantiated and called as such: * obj := Constructor(matrix); * obj.Update(row,col,val); * param_2 := obj.SumRegion(row1,col1,row2,col2); */
Solution 2
Thinking
Method 1 still walks every involved row. Replacing each Fenwick tree with a segment tree keeps point updates and in-row ranges at \(O(\log n)\) with the same meaning.
A sub-rectangle is still the sum of per-row interval sums. Explicit interval nodes make the column-range aggregation easier to read.
classNode:def__init__(self):self.l=0self.r=0self.v=0classSegmentTree:def__init__(self,nums):n=len(nums)self.nums=numsself.tr=[Node()for_inrange(4*n)]self.build(1,1,n)defbuild(self,u,l,r):self.tr[u].l=lself.tr[u].r=rifl==r:self.tr[u].v=self.nums[l-1]returnmid=(l+r)>>1self.build(u<<1,l,mid)self.build(u<<1|1,mid+1,r)self.pushup(u)defmodify(self,u,x,v):ifself.tr[u].l==xandself.tr[u].r==x:self.tr[u].v=vreturnmid=(self.tr[u].l+self.tr[u].r)>>1ifx<=mid:self.modify(u<<1,x,v)else:self.modify(u<<1|1,x,v)self.pushup(u)defquery(self,u,l,r):ifself.tr[u].l>=landself.tr[u].r<=r:returnself.tr[u].vmid=(self.tr[u].l+self.tr[u].r)>>1v=0ifl<=mid:v+=self.query(u<<1,l,r)ifr>mid:v+=self.query(u<<1|1,l,r)returnvdefpushup(self,u):self.tr[u].v=self.tr[u<<1].v+self.tr[u<<1|1].vclassNumMatrix:def__init__(self,matrix:List[List[int]]):self.trees=[SegmentTree(row)forrowinmatrix]defupdate(self,row:int,col:int,val:int)->None:tree=self.trees[row]tree.modify(1,col+1,val)defsumRegion(self,row1:int,col1:int,row2:int,col2:int)->int:returnsum(self.trees[row].query(1,col1+1,col2+1)forrowinrange(row1,row2+1))# Your NumMatrix object will be instantiated and called as such:# obj = NumMatrix(matrix)# obj.update(row,col,val)# param_2 = obj.sumRegion(row1,col1,row2,col2)
classNode{intl;intr;intv;}classSegmentTree{privateNode[]tr;privateint[]nums;publicSegmentTree(int[]nums){intn=nums.length;tr=newNode[n<<2];this.nums=nums;for(inti=0;i<tr.length;++i){tr[i]=newNode();}build(1,1,n);}publicvoidbuild(intu,intl,intr){tr[u].l=l;tr[u].r=r;if(l==r){tr[u].v=nums[l-1];return;}intmid=(l+r)>>1;build(u<<1,l,mid);build(u<<1|1,mid+1,r);pushup(u);}publicvoidmodify(intu,intx,intv){if(tr[u].l==x&&tr[u].r==x){tr[u].v=v;return;}intmid=(tr[u].l+tr[u].r)>>1;if(x<=mid){modify(u<<1,x,v);}else{modify(u<<1|1,x,v);}pushup(u);}publicvoidpushup(intu){tr[u].v=tr[u<<1].v+tr[u<<1|1].v;}publicintquery(intu,intl,intr){if(tr[u].l>=l&&tr[u].r<=r){returntr[u].v;}intmid=(tr[u].l+tr[u].r)>>1;intv=0;if(l<=mid){v+=query(u<<1,l,r);}if(r>mid){v+=query(u<<1|1,l,r);}returnv;}}classNumMatrix{privateSegmentTree[]trees;publicNumMatrix(int[][]matrix){intm=matrix.length;trees=newSegmentTree[m];for(inti=0;i<m;++i){trees[i]=newSegmentTree(matrix[i]);}}publicvoidupdate(introw,intcol,intval){SegmentTreetree=trees[row];tree.modify(1,col+1,val);}publicintsumRegion(introw1,intcol1,introw2,intcol2){ints=0;for(introw=row1;row<=row2;++row){SegmentTreetree=trees[row];s+=tree.query(1,col1+1,col2+1);}returns;}}/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * obj.update(row,col,val); * int param_2 = obj.sumRegion(row1,col1,row2,col2); */
classNode{public:intl;intr;intv;};classSegmentTree{public:vector<Node*>tr;vector<int>nums;SegmentTree(vector<int>&nums){intn=nums.size();tr.resize(n<<2);this->nums=nums;for(inti=0;i<tr.size();++i)tr[i]=newNode();build(1,1,n);}voidbuild(intu,intl,intr){tr[u]->l=l;tr[u]->r=r;if(l==r){tr[u]->v=nums[l-1];return;}intmid=(l+r)>>1;build(u<<1,l,mid);build(u<<1|1,mid+1,r);pushup(u);}voidmodify(intu,intx,intv){if(tr[u]->l==x&&tr[u]->r==x){tr[u]->v=v;return;}intmid=(tr[u]->l+tr[u]->r)>>1;if(x<=mid)modify(u<<1,x,v);elsemodify(u<<1|1,x,v);pushup(u);}intquery(intu,intl,intr){if(tr[u]->l>=l&&tr[u]->r<=r)returntr[u]->v;intmid=(tr[u]->l+tr[u]->r)>>1;intv=0;if(l<=mid)v+=query(u<<1,l,r);if(r>mid)v+=query(u<<1|1,l,r);returnv;}voidpushup(intu){tr[u]->v=tr[u<<1]->v+tr[u<<1|1]->v;}};classNumMatrix{public:vector<SegmentTree*>trees;NumMatrix(vector<vector<int>>&matrix){intm=matrix.size();trees.resize(m);for(inti=0;i<m;++i)trees[i]=newSegmentTree(matrix[i]);}voidupdate(introw,intcol,intval){SegmentTree*tree=trees[row];tree->modify(1,col+1,val);}intsumRegion(introw1,intcol1,introw2,intcol2){ints=0;for(introw=row1;row<=row2;++row)s+=trees[row]->query(1,col1+1,col2+1);returns;}};/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * obj->update(row,col,val); * int param_2 = obj->sumRegion(row1,col1,row2,col2); */