VOOZH about

URL: https://www.geeksforgeeks.org/dsa/two-dimensional-binary-indexed-tree-or-fenwick-tree/

⇱ Two Dimensional Binary Indexed Tree or Fenwick Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Two Dimensional Binary Indexed Tree or Fenwick Tree

Last Updated : 30 Nov, 2023

Prerequisite - Fenwick Tree

We know that to answer range sum queries on a 1-D array efficiently, binary indexed tree (or Fenwick Tree) is the best choice (even better than segment tree due to less memory requirements and a little faster than segment tree).

The answer is yes. This is possible using a 2D BIT which is nothing but an array of 1D BIT. 

We consider the below example. Suppose we have to find the sum of all numbers inside the highlighted area:

👁 fenwick tree

We assume the origin of the matrix at the bottom - O.Then a 2D BIT exploits the fact that-

Sum under the marked area = Sum(OB) - Sum(OD) - 
 Sum(OA) + Sum(OC) 

👁 Image

In our program, we use the getSum(x, y) function which finds the sum of the matrix from (0, 0) to (x, y). 
Hence the below formula : 

Sum under the marked area = Sum(OB) - Sum(OD) - 
 Sum(OA) + Sum(OC) 

The above formula gets reduced to,

Query(x1,y1,x2,y2) = getSum(x2, y2) - 
 getSum(x2, y1-1) - 
 getSum(x1-1, y2) + 
 getSum(x1-1, y1-1) 

where, 
x1, y1 = x and y coordinates of C 
x2, y2 = x and y coordinates of B
The updateBIT(x, y, val) function updates all the elements under the region – (x, y) to (N, M) where, 
N = maximum X co-ordinate of the whole matrix. 
M = maximum Y co-ordinate of the whole matrix.
The rest procedure is quite similar to that of 1D Binary Indexed Tree.

Below is the C++ implementation of 2D indexed tree 


Output
Query(1, 1, 3, 2) = 30
Query(2, 3, 3, 3) = 7
Query(1, 1, 1, 1) = 6

Time Complexity:

  • Both updateBIT(x, y, val) function and getSum(x, y) function takes O(log(N)*log(M)) time.
  • Building the 2D BIT takes O(NM log(N)*log(M)).
  • Since in each of the queries we are calling getSum(x, y) function so answering all the Q queries takes O(Q*log(N)*log(M)) time.
  • Hence the overall time complexity of the program is O((NM+Q)*log(N)*log(M)) where, 
    N = maximum X co-ordinate of the whole matrix. 
    M = maximum Y co-ordinate of the whole matrix. 
    Q = Number of queries.

Auxiliary Space: O(NM) to store the BIT and the auxiliary array

Comment