Skip to content

Commit a43989a

Browse files
committed
[Feature] Fenwick Tree for 1D datasets!
1 parent a984e16 commit a43989a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

structures/fenwick_tree.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
index += 1
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

Comments
 (0)