Idea behind Fenwick Trees
Consider Fenwick tree as an array F[] with 1-based indexing, such that every index of array stores Partial Sum of range. For simplicity, assume the size of F[] to be 16. Now, if we have queries to calculate the range sum in an array. So, for any index i, F[i] will store the sum of values from index j+1 to i, such that j = i – (rightmost set bit of i). Refer to the below table to understand the range of values:
Value of i | Binary Representation | Rightmost set bit of i | Value of j | Partial Sum Range [start, end] |
---|---|---|---|---|
0 | 0000 | 0000 | 0000 | – |
1 | 0001 | 0001 | 0000 | [1, 1] |
2 | 0010 | 0010 | 0000 | [1, 2] |
3 | 0011 | 0001 | 0010 | [3, 3] |
4 | 0100 | 0100 | 0000 | [1, 4] |
5 | 0101 | 0001 | 0100 | [5, 5] |
6 | 0110 | 0010 | 0100 | [5, 6] |
7 | 0111 | 0001 | 0110 | [7, 7] |
8 | 1000 | 1000 | 0000 | [1, 8] |
9 | 1001 | 0001 | 1000 | [9, 9] |
10 | 1010 | 0010 | 1000 | [9, 10] |
11 | 1011 | 0001 | 1010 | [11, 11] |
12 | 1100 | 0100 | 1000 | [9, 12] |
13 | 1101 | 0001 | 1100 | [13, 13] |
14 | 1110 | 0010 | 1100 | [13, 14] |
15 | 1111 | 0001 | 1110 | [15, 15] |
So, from the above table we can see that each index of Fenwick tree F[] stores the sum of range. Now, if we need to calculate the prefix sum till 7th element, then instead of iterating from 1 to 7 and calculating the sum, we can take the sum of F[7] + F[6] + F[4]. Similarly, to calculate the prefix sum till 13th element, we can take the sum of F[13] + F[12] + F[8] to get the prefix sum. So, in other words if we want to calculate the prefix sum till ith element, we can add elements of array F[] present at indices which are obtained by removing the last set bit of i, one by one.
Prefix Sum till 7th element = F[7] + F[6] + F[4],
7 –remove right most set bit –> 6 –remove right most set bit –> 4 –remove right most set bit –> 0Prefix Sum till 13th element = F[13] + F[12] + F[8],
13 –remove right most set bit –> 12 –remove right most set bit –> 8 –remove right most set bit –> 0
Now, in order to calculate the range sum of [L, R], we can simply subtract the prefix sum till [L-1] from prefix sum till R.
Fenwick Tree (Binary Indexed Tree) for Competitive Programming
In the world of competitive programming, speed is everything. Fenwick Tree (also known as Binary Indexed Tree), created by Peter M. Fenwick. They’re like secret weapons for programmers, especially when you need to quickly find cumulative frequencies in problem-solving. This article breaks down Fenwick Trees in simple terms—how they’re built and why they’re handy for competitive programming. Whether you’re starting out or a pro looking for a speed boost, Fenwick Trees could be your key to success in coding competitions. Let’s dive in!
Contact Us