max-priority-queue-typed 2.4.4 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +63 -0
  2. package/dist/cjs/index.cjs +403 -98
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs-legacy/index.cjs +402 -97
  5. package/dist/cjs-legacy/index.cjs.map +1 -1
  6. package/dist/esm/index.mjs +403 -99
  7. package/dist/esm/index.mjs.map +1 -1
  8. package/dist/esm-legacy/index.mjs +402 -98
  9. package/dist/esm-legacy/index.mjs.map +1 -1
  10. package/dist/types/common/error.d.ts +23 -0
  11. package/dist/types/common/index.d.ts +1 -0
  12. package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
  13. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +128 -51
  14. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +210 -164
  15. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +439 -78
  16. package/dist/types/data-structures/binary-tree/bst.d.ts +311 -28
  17. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +217 -31
  18. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +218 -152
  19. package/dist/types/data-structures/binary-tree/tree-map.d.ts +1281 -5
  20. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +1087 -201
  21. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +858 -65
  22. package/dist/types/data-structures/binary-tree/tree-set.d.ts +1133 -5
  23. package/dist/types/data-structures/graph/abstract-graph.d.ts +44 -0
  24. package/dist/types/data-structures/graph/directed-graph.d.ts +220 -47
  25. package/dist/types/data-structures/graph/map-graph.d.ts +59 -1
  26. package/dist/types/data-structures/graph/undirected-graph.d.ts +218 -59
  27. package/dist/types/data-structures/hash/hash-map.d.ts +230 -77
  28. package/dist/types/data-structures/heap/heap.d.ts +287 -99
  29. package/dist/types/data-structures/heap/max-heap.d.ts +46 -0
  30. package/dist/types/data-structures/heap/min-heap.d.ts +59 -0
  31. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +286 -44
  32. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +278 -65
  33. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +415 -12
  34. package/dist/types/data-structures/matrix/matrix.d.ts +331 -0
  35. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +57 -0
  36. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +60 -0
  37. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +60 -0
  38. package/dist/types/data-structures/queue/deque.d.ts +313 -66
  39. package/dist/types/data-structures/queue/queue.d.ts +211 -42
  40. package/dist/types/data-structures/stack/stack.d.ts +174 -32
  41. package/dist/types/data-structures/trie/trie.d.ts +213 -43
  42. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -1
  43. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +1 -4
  44. package/dist/types/types/data-structures/queue/deque.d.ts +6 -0
  45. package/dist/umd/max-priority-queue-typed.js +400 -95
  46. package/dist/umd/max-priority-queue-typed.js.map +1 -1
  47. package/dist/umd/max-priority-queue-typed.min.js +1 -1
  48. package/dist/umd/max-priority-queue-typed.min.js.map +1 -1
  49. package/package.json +2 -2
  50. package/src/common/error.ts +60 -0
  51. package/src/common/index.ts +2 -0
  52. package/src/data-structures/base/iterable-element-base.ts +2 -2
  53. package/src/data-structures/binary-tree/avl-tree.ts +134 -51
  54. package/src/data-structures/binary-tree/binary-indexed-tree.ts +303 -247
  55. package/src/data-structures/binary-tree/binary-tree.ts +542 -121
  56. package/src/data-structures/binary-tree/bst.ts +346 -37
  57. package/src/data-structures/binary-tree/red-black-tree.ts +309 -96
  58. package/src/data-structures/binary-tree/segment-tree.ts +372 -248
  59. package/src/data-structures/binary-tree/tree-map.ts +1292 -13
  60. package/src/data-structures/binary-tree/tree-multi-map.ts +1098 -215
  61. package/src/data-structures/binary-tree/tree-multi-set.ts +863 -69
  62. package/src/data-structures/binary-tree/tree-set.ts +1143 -15
  63. package/src/data-structures/graph/abstract-graph.ts +106 -1
  64. package/src/data-structures/graph/directed-graph.ts +223 -47
  65. package/src/data-structures/graph/map-graph.ts +59 -1
  66. package/src/data-structures/graph/undirected-graph.ts +299 -59
  67. package/src/data-structures/hash/hash-map.ts +243 -79
  68. package/src/data-structures/heap/heap.ts +291 -102
  69. package/src/data-structures/heap/max-heap.ts +48 -3
  70. package/src/data-structures/heap/min-heap.ts +59 -0
  71. package/src/data-structures/linked-list/doubly-linked-list.ts +286 -44
  72. package/src/data-structures/linked-list/singly-linked-list.ts +278 -65
  73. package/src/data-structures/linked-list/skip-linked-list.ts +689 -90
  74. package/src/data-structures/matrix/matrix.ts +425 -22
  75. package/src/data-structures/priority-queue/max-priority-queue.ts +59 -3
  76. package/src/data-structures/priority-queue/min-priority-queue.ts +60 -0
  77. package/src/data-structures/priority-queue/priority-queue.ts +60 -0
  78. package/src/data-structures/queue/deque.ts +343 -68
  79. package/src/data-structures/queue/queue.ts +211 -42
  80. package/src/data-structures/stack/stack.ts +174 -32
  81. package/src/data-structures/trie/trie.ts +215 -44
  82. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -1
  83. package/src/types/data-structures/linked-list/skip-linked-list.ts +2 -1
  84. package/src/types/data-structures/queue/deque.ts +7 -0
  85. package/src/utils/utils.ts +4 -2
@@ -5,327 +5,383 @@
5
5
  * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
6
6
  * @license MIT License
7
7
  */
8
- import { getMSB } from '../../utils';
8
+ import { ERR } from '../../common';
9
9
 
10
10
  /**
11
+ * Binary Indexed Tree (Fenwick Tree).
11
12
  *
13
+ * Efficient prefix sums and point updates in O(log n).
14
+ * Standard array-based implementation per C++ competitive programming conventions.
15
+ *
16
+ * All indices are 0-based externally; internally converted to 1-based for BIT arithmetic.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const bit = new BinaryIndexedTree(6);
21
+ * bit.update(0, 3); // index 0 += 3
22
+ * bit.update(1, 2); // index 1 += 2
23
+ * bit.update(2, 7); // index 2 += 7
24
+ *
25
+ * bit.query(2); // prefix sum [0..2] = 12
26
+ * bit.queryRange(1, 2); // range sum [1..2] = 9
27
+ * bit.get(1); // point value at index 1 = 2
28
+ * ```
12
29
  */
13
- export class BinaryIndexedTree {
14
- protected readonly _freq: number;
15
- protected readonly _max: number;
16
-
17
- /**
18
- * The constructor initializes the properties of an object, including default frequency, maximum
19
- * value, a freqMap data structure, the most significant bit, and the count of negative frequencies.
20
- * @param - - `frequency`: The default frequency value. It is optional and has a default
21
- * value of 0.
22
- */
23
- constructor({ frequency = 0, max }: { frequency?: number; max: number }) {
24
- this._freq = frequency;
25
- this._max = max;
26
- this._freqMap = { 0: 0 };
27
- this._msb = getMSB(max);
28
- this._negativeCount = frequency < 0 ? max : 0;
29
- }
30
-
31
- protected _freqMap: Record<number, number>;
32
-
33
- /**
34
- * The function returns the frequency map of numbers.
35
- * @returns The `_freqMap` property, which is a record with number keys and number values, is being
36
- * returned.
37
- */
38
- get freqMap(): Record<number, number> {
39
- return this._freqMap;
40
- }
41
-
42
- protected _msb: number;
43
-
44
- /**
45
- * The function returns the value of the _msb property.
46
- * @returns The `_msb` property of the object.
47
- */
48
- get msb(): number {
49
- return this._msb;
50
- }
51
-
52
- protected _negativeCount: number;
30
+ export class BinaryIndexedTree implements Iterable<number> {
31
+ protected readonly _size: number;
32
+ protected _tree: number[]; // 1-indexed BIT array
53
33
 
54
34
  /**
55
- * The function returns the value of the _negativeCount property.
56
- * @returns The method is returning the value of the variable `_negativeCount`, which is of type
57
- * `number`.
35
+ * Construct a BIT of given size (all zeros), or from an initial values array.
36
+ * @param sizeOrElements - number of elements, or an array of initial values
58
37
  */
59
- get negativeCount(): number {
60
- return this._negativeCount;
38
+ constructor(sizeOrElements: number | number[]) {
39
+ if (Array.isArray(sizeOrElements)) {
40
+ this._size = sizeOrElements.length;
41
+ this._tree = new Array(this._size + 1).fill(0);
42
+ for (let i = 0; i < this._size; i++) {
43
+ this._pointUpdate(i + 1, sizeOrElements[i]);
44
+ }
45
+ } else {
46
+ if (!Number.isInteger(sizeOrElements) || sizeOrElements < 0) {
47
+ throw new RangeError(ERR.invalidArgument('size must be a non-negative integer', 'BinaryIndexedTree'));
48
+ }
49
+ this._size = sizeOrElements;
50
+ this._tree = new Array(this._size + 1).fill(0);
51
+ }
61
52
  }
62
53
 
63
- /**
64
- * The above function returns the value of the protected variable `_freq`.
65
- * @returns The frequency value stored in the protected variable `_freq`.
66
- */
67
- get freq(): number {
68
- return this._freq;
69
- }
54
+ // ─── Core operations ──────────────────────────────────────────
70
55
 
71
56
  /**
72
- * The above function returns the maximum value.
73
- * @returns The maximum value stored in the variable `_max`.
57
+ * Point update: add delta to the value at index (0-based).
58
+ * Time: O(log n)
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+ * @example
74
+ * // Add delta at index
75
+ * const bit = new BinaryIndexedTree([1, 2, 3, 4, 5]);
76
+ * bit.update(2, 7);
77
+ * console.log(bit.get(2)); // 10;
74
78
  */
75
- get max(): number {
76
- return this._max;
79
+ update(index: number, delta: number): void {
80
+ this._checkIndex(index);
81
+ this._pointUpdate(index + 1, delta);
77
82
  }
78
83
 
79
84
  /**
80
- * The function "readSingle" reads a single number from a specified index.
81
- * @param {number} index - The `index` parameter is a number that represents the index of an element in a
82
- * collection or array.
83
- * @returns a number.
85
+ * Point set: set the value at index to an absolute value (0-based).
86
+ * Time: O(log n)
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+ * @example
103
+ * // Set value at index
104
+ * const bit = new BinaryIndexedTree([1, 2, 3]);
105
+ * bit.set(1, 10);
106
+ * console.log(bit.get(1)); // 10;
84
107
  */
85
- readSingle(index: number): number {
108
+ set(index: number, value: number): void {
86
109
  this._checkIndex(index);
87
- return this._readSingle(index);
110
+ const current = this.get(index);
111
+ this._pointUpdate(index + 1, value - current);
88
112
  }
89
113
 
90
114
  /**
91
- * The "update" function updates the value at a given index by adding a delta and triggers a callback
92
- * to notify of the change.
93
- * @param {number} position - The `index` parameter represents the index of the element that needs to be
94
- * updated in the data structure.
95
- * @param {number} change - The "delta" parameter represents the change in value that needs to be
96
- * applied to the frequency at the specified index.
115
+ * Get the point value at index (0-based).
116
+ * Time: O(log n)
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+ * @example
132
+ * // Get value at index
133
+ * const bit = new BinaryIndexedTree([1, 2, 3]);
134
+ * console.log(bit.get(0)); // 1;
135
+ * console.log(bit.get(2)); // 3;
97
136
  */
98
- update(position: number, change: number): void {
99
- this._checkIndex(position);
100
- const freqCur = this._readSingle(position);
101
-
102
- this._update(position, change);
103
- this._updateNegativeCount(freqCur, freqCur + change);
137
+ get(index: number): number {
138
+ this._checkIndex(index);
139
+ return this._pointQuery(index + 1);
104
140
  }
105
141
 
106
142
  /**
107
- * The function "writeSingle" checks the index and writes a single value with a given frequency.
108
- * @param {number} index - The `index` parameter is a number that represents the index of an element. It
109
- * is used to identify the specific element that needs to be written.
110
- * @param {number} freq - The `freq` parameter represents the frequency value that needs to be
111
- * written.
143
+ * Prefix sum query: returns sum of elements [0..index] (inclusive, 0-based).
144
+ * Time: O(log n)
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+ * @example
161
+ * // Prefix sum
162
+ * const bit = new BinaryIndexedTree([1, 2, 3, 4]);
163
+ * console.log(bit.query(2)); // 6;
112
164
  */
113
- writeSingle(index: number, freq: number): void {
165
+ query(index: number): number {
114
166
  this._checkIndex(index);
115
- this._writeSingle(index, freq);
167
+ return this._prefixSum(index + 1);
116
168
  }
117
169
 
118
170
  /**
119
- * The read function takes a count parameter, checks if it is an integer, and returns the result of
120
- * calling the _read function with the count parameter clamped between 0 and the maximum value.
121
- * @param {number} count - The `count` parameter is a number that represents the number of items to
122
- * read.
123
- * @returns a number.
171
+ * Range sum query: returns sum of elements [start..end] (inclusive, 0-based).
172
+ * Time: O(log n)
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+ * @example
188
+ * // Range sum
189
+ * const bit = new BinaryIndexedTree([1, 2, 3, 4]);
190
+ * console.log(bit.queryRange(1, 2)); // 5;
124
191
  */
125
- read(count: number): number {
126
- if (!Number.isInteger(count)) {
127
- throw new Error('Invalid count');
128
- }
129
- return this._read(Math.max(Math.min(count, this.max), 0));
192
+ queryRange(start: number, end: number): number {
193
+ this._checkIndex(start);
194
+ this._checkIndex(end);
195
+ if (start > end) return 0;
196
+ if (start === 0) return this._prefixSum(end + 1);
197
+ return this._prefixSum(end + 1) - this._prefixSum(start);
130
198
  }
131
199
 
200
+ // ─── Binary search ───────────────────────────────────────────
201
+
132
202
  /**
133
- * The function returns the lower bound of a non-descending sequence that sums up to a given number.
134
- * @param {number} sum - The `sum` parameter is a number that represents the target sum that we want
135
- * to find in the sequence.
136
- * @returns The lowerBound function is returning a number.
203
+ * Find the smallest index i such that prefix sum [0..i] >= sum.
204
+ * Requires all values to be non-negative (behavior undefined otherwise).
205
+ * Returns size if no such index exists.
206
+ * Time: O(log n)
207
+
208
+
209
+
210
+
211
+
212
+
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+ * @example
223
+ * // Find index with prefix sum ≥ target
224
+ * const bit = new BinaryIndexedTree([1, 2, 3, 4]);
225
+ * const idx = bit.lowerBound(4);
226
+ * console.log(idx); // >= 0;
137
227
  */
138
228
  lowerBound(sum: number): number {
139
- if (this.negativeCount > 0) {
140
- throw new Error('Sequence is not non-descending');
229
+ let pos = 0;
230
+ let bitMask = this._highBit(this._size);
231
+
232
+ while (bitMask > 0) {
233
+ const next = pos + bitMask;
234
+ if (next <= this._size && this._tree[next] < sum) {
235
+ sum -= this._tree[next];
236
+ pos = next;
237
+ }
238
+ bitMask >>= 1;
141
239
  }
142
- return this._binarySearch(sum, (x, y) => x < y);
143
- }
144
240
 
145
- /**
146
- * The upperBound function returns the index of the first element in a sequence that is greater than
147
- * or equal to a given sum.
148
- * @param {number} sum - The "sum" parameter is a number that represents the target sum that we want
149
- * to find in the sequence.
150
- * @returns The upperBound function is returning a number.
151
- */
152
- upperBound(sum: number): number {
153
- if (this.negativeCount > 0) {
154
- throw new Error('Must not be descending');
155
- }
156
- return this._binarySearch(sum, (x, y) => x <= y);
241
+ return pos; // 0-based
157
242
  }
158
243
 
159
244
  /**
160
- * The function calculates the prefix sum of an array using a binary indexed tree.
161
- * @param {number} i - The parameter "i" in the function "getPrefixSum" represents the index of the element in the
162
- * array for which we want to calculate the prefix sum.
163
- * @returns The function `getPrefixSum` returns the prefix sum of the elements in the binary indexed tree up to index
164
- * `i`.
245
+ * Find the smallest index i such that prefix sum [0..i] > sum.
246
+ * Requires all values to be non-negative (behavior undefined otherwise).
247
+ * Returns size if no such index exists.
248
+ * Time: O(log n)
249
+
250
+
251
+ * @example
252
+ * // Find index with prefix sum > target
253
+ * const bit = new BinaryIndexedTree([1, 2, 3, 4]);
254
+ * const idx = bit.upperBound(4);
255
+ * console.log(idx); // >= 0;
165
256
  */
166
- getPrefixSum(i: number): number {
167
- this._checkIndex(i);
168
- i++; // Convert to 1-based index
169
-
170
- let sum = 0;
171
- while (i > 0) {
172
- sum += this._getFrequency(i);
173
- i -= i & -i;
257
+ upperBound(sum: number): number {
258
+ let pos = 0;
259
+ let bitMask = this._highBit(this._size);
260
+
261
+ while (bitMask > 0) {
262
+ const next = pos + bitMask;
263
+ if (next <= this._size && this._tree[next] <= sum) {
264
+ sum -= this._tree[next];
265
+ pos = next;
266
+ }
267
+ bitMask >>= 1;
174
268
  }
175
269
 
176
- return sum;
270
+ return pos; // 0-based
177
271
  }
178
272
 
179
- /**
180
- * The function returns the value of a specific index in a freqMap data structure, or a default value if
181
- * the index is not found.
182
- * @param {number} index - The `index` parameter is a number that represents the index of a node in a
183
- * freqMap data structure.
184
- * @returns a number.
185
- */
186
- protected _getFrequency(index: number): number {
187
- if (index in this.freqMap) {
188
- return this.freqMap[index];
189
- }
273
+ // ─── Standard interface ──────────────────────────────────────
190
274
 
191
- return this.freq * (index & -index);
275
+ get size(): number {
276
+ return this._size;
192
277
  }
193
278
 
194
- /**
195
- * The function _updateFrequency adds a delta value to the element at the specified index in the freqMap array.
196
- * @param {number} index - The index parameter is a number that represents the index of the freqMap
197
- * element that needs to be updated.
198
- * @param {number} delta - The `delta` parameter represents the change in value that needs to be
199
- * added to the freqMap at the specified `index`.
200
- */
201
- protected _updateFrequency(index: number, delta: number): void {
202
- this.freqMap[index] = this._getFrequency(index) + delta;
279
+ isEmpty(): boolean {
280
+ return this._size === 0;
203
281
  }
204
282
 
205
- /**
206
- * The function checks if the given index is valid and within the range.
207
- * @param {number} index - The parameter "index" is of type number and represents the index value
208
- * that needs to be checked.
209
- */
210
- protected _checkIndex(index: number): void {
211
- if (!Number.isInteger(index)) {
212
- throw new Error('Invalid index: Index must be an integer.');
213
- }
214
- if (index < 0 || index >= this.max) {
215
- throw new Error('Index out of range: Index must be within the range [0, this.max).');
216
- }
283
+ clear(): void {
284
+ this._tree.fill(0);
217
285
  }
218
286
 
219
- /**
220
- * The function calculates the sum of elements in an array up to a given index using a binary indexed
221
- * freqMap.
222
- * @param {number} index - The `index` parameter is a number that represents the index of an element in a
223
- * data structure.
224
- * @returns a number.
225
- */
226
- protected _readSingle(index: number): number {
227
- index = index + 1;
228
- let sum = this._getFrequency(index);
229
- const z = index - (index & -index);
230
-
231
- index--;
232
-
233
- while (index !== z) {
234
- sum -= this._getFrequency(index);
235
- index -= index & -index;
236
- }
237
-
238
- return sum;
287
+ clone(): BinaryIndexedTree {
288
+ return new BinaryIndexedTree(this.toArray());
239
289
  }
240
290
 
241
291
  /**
242
- * The function `_updateNegativeCount` updates a counter based on changes in frequency values.
243
- * @param {number} freqCur - The current frequency value.
244
- * @param {number} freqNew - The freqNew parameter represents the new frequency value.
292
+ * Returns the point values as a plain array.
293
+ * Time: O(n log n)
294
+
295
+
296
+ * @example
297
+ * // Convert to array
298
+ * const bit = new BinaryIndexedTree([1, 2, 3]);
299
+ * console.log(bit.toArray()); // [1, 2, 3];
245
300
  */
246
- protected _updateNegativeCount(freqCur: number, freqNew: number): void {
247
- if (freqCur < 0 && freqNew >= 0) {
248
- this._negativeCount--;
249
- } else if (freqCur >= 0 && freqNew < 0) {
250
- this._negativeCount++;
301
+ toArray(): number[] {
302
+ const result: number[] = [];
303
+ for (let i = 0; i < this._size; i++) {
304
+ result.push(this._pointQuery(i + 1));
251
305
  }
306
+ return result;
252
307
  }
253
308
 
254
309
  /**
255
- * The `_update` function updates the values in a binary indexed freqMap starting from a given index and
256
- * propagating the changes to its parent nodes.
257
- * @param {number} index - The `index` parameter is a number that represents the index of the element in
258
- * the data structure that needs to be updated.
259
- * @param {number} delta - The `delta` parameter represents the change in value that needs to be
260
- * applied to the elements in the data structure.
310
+ * Iterate over point values in index order.
261
311
  */
262
- protected _update(index: number, delta: number): void {
263
- index = index + 1;
312
+ [Symbol.iterator](): IterableIterator<number> {
313
+ const size = this._size;
314
+ let i = 0;
315
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
316
+ const self = this;
317
+ return {
318
+ [Symbol.iterator]() {
319
+ return this;
320
+ },
321
+ next(): IteratorResult<number> {
322
+ if (i < size) {
323
+ return { value: self._pointQuery(i++ + 1), done: false };
324
+ }
325
+ return { value: undefined as any, done: true };
326
+ }
327
+ };
328
+ }
264
329
 
265
- while (index <= this.max) {
266
- this._updateFrequency(index, delta);
267
- index += index & -index;
330
+ forEach(callback: (value: number, index: number) => void): void {
331
+ for (let i = 0; i < this._size; i++) {
332
+ callback(this._pointQuery(i + 1), i);
268
333
  }
269
334
  }
270
335
 
271
- /**
272
- * The `_writeSingle` function updates the frequency at a specific index and triggers a callback if
273
- * the frequency has changed.
274
- * @param {number} index - The `index` parameter is a number that represents the index of the element
275
- * being modified or accessed.
276
- * @param {number} freq - The `freq` parameter represents the new frequency value that needs to be
277
- * written to the specified index `index`.
278
- */
279
- protected _writeSingle(index: number, freq: number): void {
280
- const freqCur = this._readSingle(index);
281
-
282
- this._update(index, freq - freqCur);
283
- this._updateNegativeCount(freqCur, freq);
336
+ print(): void {
337
+ console.log(this.toArray());
284
338
  }
285
339
 
286
- /**
287
- * The `_read` function calculates the sum of values in a binary freqMap up to a given count.
288
- * @param {number} count - The `count` parameter is a number that represents the number of elements
289
- * to read from the freqMap.
290
- * @returns the sum of the values obtained from calling the `_getFrequency` method for each index in the
291
- * range from `count` to 1.
292
- */
293
- protected _read(count: number): number {
294
- let index = count;
340
+ // ─── Internal helpers ─────────────────────────────────────────
341
+
342
+ /** 1-based prefix sum up to pos (inclusive). */
343
+ protected _prefixSum(pos: number): number {
295
344
  let sum = 0;
296
- while (index) {
297
- sum += this._getFrequency(index);
298
- index -= index & -index;
345
+ while (pos > 0) {
346
+ sum += this._tree[pos];
347
+ pos -= pos & -pos;
299
348
  }
300
-
301
349
  return sum;
302
350
  }
303
351
 
304
- /**
305
- * The function `_binarySearch` performs a binary search to find the largest number that satisfies a given
306
- * condition.
307
- * @param {number} sum - The sum parameter is a number that represents the target sum value.
308
- * @param before - The `before` parameter is a function that takes two numbers `x` and `y` as
309
- * arguments and returns a boolean value. It is used to determine if `x` is less than or equal to
310
- * `y`. The purpose of this function is to compare two numbers and determine their order.
311
- * @returns the value of the variable "left".
312
- */
313
- protected _binarySearch(sum: number, before: (x: number, y: number) => boolean): number {
314
- let left = 0;
315
- let right = this.msb << 1;
316
- let sumT = sum;
352
+ /** 1-based point update: add delta to position pos. */
353
+ protected _pointUpdate(pos: number, delta: number): void {
354
+ while (pos <= this._size) {
355
+ this._tree[pos] += delta;
356
+ pos += pos & -pos;
357
+ }
358
+ }
317
359
 
318
- while (right > left + 1) {
319
- const middle = (left + right) >> 1;
320
- const sumM = this._getFrequency(middle);
360
+ /** 1-based point query: get exact value at pos. */
361
+ protected _pointQuery(pos: number): number {
362
+ let val = this._tree[pos];
363
+ const lca = pos - (pos & -pos); // parent in prefix-sum sense
364
+ pos--;
365
+ while (pos > lca) {
366
+ val -= this._tree[pos];
367
+ pos -= pos & -pos;
368
+ }
369
+ return val;
370
+ }
321
371
 
322
- if (middle <= this.max && before(sumM, sumT)) {
323
- sumT -= sumM;
324
- left = middle;
325
- } else {
326
- right = middle;
327
- }
372
+ protected _checkIndex(index: number): void {
373
+ if (!Number.isInteger(index)) {
374
+ throw new TypeError(ERR.invalidIndex('BinaryIndexedTree'));
375
+ }
376
+ if (index < 0 || index >= this._size) {
377
+ throw new RangeError(ERR.indexOutOfRange(index, 0, this._size - 1, 'BinaryIndexedTree'));
328
378
  }
329
- return left;
379
+ }
380
+
381
+ /** Returns highest power of 2 <= n. */
382
+ protected _highBit(n: number): number {
383
+ let bit = 1;
384
+ while (bit <= n) bit <<= 1;
385
+ return bit >> 1;
330
386
  }
331
387
  }