-
-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Expand file tree
/
Copy pathFenwickTree.js
More file actions
56 lines (49 loc) · 1.02 KB
/
Copy pathFenwickTree.js
File metadata and controls
56 lines (49 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Time Complexity:
* Update: O(log n)
* Query: O(log n)
* Range Query: O(log n)
*
* Space Complexity: O(n)
*
*/
export default class FenwickTree {
constructor(size) {
this.size = size
this.tree = new Array(size + 1).fill(0)
}
static fromArray(arr) {
const ft = new FenwickTree(arr.length)
for (let i = 0; i < arr.length; i++) {
ft.update(i, arr[i])
}
return ft
}
update(index, delta) {
let i = index + 1
while (i <= this.size) {
this.tree[i] += delta
i += i & -i // Adding the lowest set bit
}
}
query(index) {
let i = index + 1
let sum = 0
while (i > 0) {
sum += this.tree[i]
i -= i & -i // Removing the lowest set bit
}
return sum
}
rangeQuery(left, right) {
if (left === 0) return this.query(right)
return this.query(right) - this.query(left - 1)
}
get(index) {
return this.rangeQuery(index, index)
}
set(index, value) {
const current = this.get(index)
this.update(index, value - current)
}
}