We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a984e16 commit a43989aCopy full SHA for a43989a
structures/fenwick_tree.py
@@ -0,0 +1,29 @@
1
+class FenwickTree:
2
+
3
+ def __init__(self, arr):
4
+ self.tree = [0] * (len(arr)+1)
5
6
+ for i in range(len(arr)):
7
+ self.update(i,arr[i])
8
9
+ def update(self, index, value):
10
+ index += 1
11
+ while index <= len(self.tree)-1:
12
+ self.tree[index] += value
13
+ index += index & (-index)
14
15
+ def sum_of_n(self, index):
16
+ s = 0
17
18
19
+ while index > 0:
20
+ s += self.tree[index]
21
+ index -= index & (-index)
22
23
+ return s
24
25
+ def sum_of_range(self, start, end):
26
+ # minus 1 from start since the range is (s, e) inclusive on both ends
27
+ start -= 1
28
+ print(self.sum_of_n(end), self.sum_of_n(start))
29
+ return self.sum_of_n(end) - self.sum_of_n(start)
0 commit comments