Repository navigation
Expand file tree
/
Copy pathfenwick-tree.ts
More file actions
54 lines (49 loc) · 1.98 KB
/
Copy pathfenwick-tree.ts
File metadata and controls
54 lines (49 loc) · 1.98 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
/**
* Fenwick tree (binary indexed tree)
*
* Idea: store partial sums so that both "add x at position i" and "sum of the
* first k values" touch only O(log n) cells. With 1-based indices, cell `i`
* holds the sum of the `i & -i` values ending at `i` (`i & -i` isolates the
* lowest set bit). Prefix sums walk down by removing that bit; updates walk
* up by adding it.
*
* Compared with a segment tree: less code and half the memory, but it only
* fits operations with an inverse (sums, XOR), not min/max over ranges.
*
* Complexity: build O(n), add O(log n), prefixSum / rangeSum O(log n),
* space O(n).
*/
export class FenwickTree {
private readonly tree: number[];
constructor(sizeOrValues: number | readonly number[]) {
const values = typeof sizeOrValues === "number" ? new Array<number>(sizeOrValues).fill(0) : sizeOrValues;
const n = values.length;
this.tree = new Array<number>(n + 1).fill(0);
// O(n) build: push each cell's total into its parent once.
for (let i = 1; i <= n; i++) {
this.tree[i] = (this.tree[i] as number) + (values[i - 1] as number);
const parent = i + (i & -i);
if (parent <= n) this.tree[parent] = (this.tree[parent] as number) + (this.tree[i] as number);
}
}
get size(): number {
return this.tree.length - 1;
}
/** Adds `delta` to the value at 0-based `index`. */
add(index: number, delta: number): void {
if (index < 0 || index >= this.size) throw new RangeError(`index ${index} is out of range`);
for (let i = index + 1; i <= this.size; i += i & -i) {
this.tree[i] = (this.tree[i] as number) + delta;
}
}
/** Sum of the first `count` values, i.e. positions [0, count). */
prefixSum(count: number): number {
let sum = 0;
for (let i = Math.min(count, this.size); i > 0; i -= i & -i) sum += this.tree[i] as number;
return sum;
}
/** Sum of positions [left, right). */
rangeSum(left: number, right: number): number {
return this.prefixSum(right) - this.prefixSum(left);
}
}