Skip to content

Commit b68589f

Browse files
committed
to calculate prefix sum effieciently when there are lot of updates
1 parent 342bf3a commit b68589f

File tree

1 file changed

+82
-1
lines changed

1 file changed

+82
-1
lines changed

Fenwick_Tree/fenwickTree.java

+82-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,82 @@
1-
1+
/*
2+
3+
Space Complexity - O(n)
4+
T.C. to create - O(nlogn)
5+
T.C. to update - O(logn)
6+
T.C. to get prefix sum - O(logn)
7+
8+
*/
9+
10+
public class fenwickTree {
11+
12+
/*
13+
For updating the value in tree, we start from index + 1 and we keep adding the value for next nodes,
14+
till we reach an outside range of trees.
15+
*/
16+
17+
public void updateBinaryIndexedTree(int binaryIndexedTree[], int val, int index) {
18+
while (index < binaryIndexedTree.length) {
19+
binaryIndexedTree[index] += val; // adding to original value in node
20+
index = getIndex(index); // getting next index
21+
22+
}
23+
}
24+
25+
/*
26+
To get sum from (0, index), we start from index + 1 node and keep going up
27+
via parent to reach 0.
28+
*/
29+
30+
public int getSum(int binaryIndexedTree[], int index) {
31+
index = index + 1;
32+
int sum = 0;
33+
while (index > 0) {
34+
sum = sum + binaryIndexedTree[index];
35+
index = getParent(index);
36+
}
37+
return sum;
38+
}
39+
40+
/*
41+
Creating the Fenwick tree is like updating fenwick tree for every value in the array.
42+
*/
43+
44+
public int[] createTree(int[] input) {
45+
int binaryIndexedTree[] = new int[input.length + 1];
46+
for (int i=1; i<= input.length; i++) {
47+
updateBinaryIndexedTree(binaryIndexedTree, input[i-1], i); // 0th index value of input, will be stored at 1
48+
}
49+
return binaryIndexedTree;
50+
}
51+
52+
/*
53+
To get parent
54+
1) Get 2's complement (Flip all bits and add 1) (minus of index)
55+
2) AND it with current INDEX
56+
3) SUBTRACT it from the index
57+
*/
58+
59+
public int getParent(int index) {
60+
return index - (index & -index);
61+
}
62+
63+
/*
64+
To get next
65+
1) Get 2's complement (minus of index)
66+
2) AND it with current INDEX
67+
3) ADD it to the index
68+
*/
69+
70+
public int getNext(int index) {
71+
return index + (index & -index);
72+
}
73+
74+
public static void main(String[] args) {
75+
int[] input = {1,2,3,4,5,6,7};
76+
fenwickTree ft = new fenwickTree();
77+
int[] binaryIndexedTree = ft.createTree(input);
78+
assert 1 == ft.getSum(binaryIndexedTree, 0);
79+
assert 3 == ft.getSum(binaryIndexedTree, 1);
80+
assert 6 == ft.getSum(binaryIndexedTree, 2);
81+
}
82+
}

0 commit comments

Comments
 (0)