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
@@ -6,319 +6,443 @@
6
6
  * @license MIT License
7
7
  */
8
8
 
9
- import type { SegmentTreeNodeVal } from '../../types';
9
+ export type SegmentTreeOptions<E> = {
10
+ merger: (a: E, b: E) => E;
11
+ identity: E;
12
+ };
10
13
 
11
- export class SegmentTreeNode {
12
- /**
13
- * The constructor initializes the properties of a SegmentTreeNode object.
14
- * @param {number} start - The `start` parameter represents the starting index of the segment covered
15
- * by this node in a segment tree.
16
- * @param {number} end - The `end` parameter represents the end index of the segment covered by this
17
- * node in a segment tree.
18
- * @param {number} sum - The `sum` parameter represents the sum of the values in the range covered by
19
- * the segment tree node.
20
- * @param {SegmentTreeNodeVal | undefined} [value] - The `value` parameter is an optional parameter
21
- * of type `SegmentTreeNodeVal`. It represents the value associated with the segment tree node.
22
- */
23
- constructor(start: number, end: number, sum: number, value?: SegmentTreeNodeVal | undefined) {
24
- this._start = start;
25
- this._end = end;
26
- this._sum = sum;
27
- this._value = value || undefined;
14
+ /**
15
+ * Generic Segment Tree with flat array internals.
16
+ *
17
+ * Supports any associative merge operation (sum, min, max, gcd, etc.).
18
+ * Reference: AtCoder Library segtree<S, op, e>.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const sumTree = SegmentTree.sum([1, 2, 3, 4, 5]);
23
+ * sumTree.query(1, 3); // 9 (2+3+4)
24
+ * sumTree.update(2, 10); // [1, 2, 10, 4, 5]
25
+ * sumTree.query(1, 3); // 16 (2+10+4)
26
+ *
27
+ * const minTree = SegmentTree.min([5, 2, 8, 1, 9]);
28
+ * minTree.query(0, 4); // 1
29
+ * ```
30
+ */
31
+ export class SegmentTree<E = number> implements Iterable<E> {
32
+ protected readonly _merger: (a: E, b: E) => E;
33
+ protected readonly _identity: E;
34
+ protected _n: number; // number of leaf elements
35
+ protected _tree: E[]; // flat array, 1-indexed, size 2*_size
36
+ protected _treeSize: number; // internal tree size (next power of 2 >= _n)
37
+
38
+ constructor(elements: E[], options: SegmentTreeOptions<E>) {
39
+ this._merger = options.merger;
40
+ this._identity = options.identity;
41
+ this._n = elements.length;
42
+
43
+ // Round up to next power of 2
44
+ this._treeSize = 1;
45
+ while (this._treeSize < this._n) this._treeSize <<= 1;
46
+
47
+ // Allocate and fill with identity
48
+ this._tree = new Array(2 * this._treeSize).fill(this._identity);
49
+
50
+ // Place elements in leaves
51
+ for (let i = 0; i < this._n; i++) {
52
+ this._tree[this._treeSize + i] = elements[i];
53
+ }
54
+
55
+ // Build internal nodes bottom-up
56
+ for (let i = this._treeSize - 1; i >= 1; i--) {
57
+ this._tree[i] = this._merger(this._tree[2 * i], this._tree[2 * i + 1]);
58
+ }
28
59
  }
29
60
 
30
- protected _start = 0;
61
+ // ─── Convenience factories ─────────────────────────────────
31
62
 
32
63
  /**
33
- * The function returns the value of the protected variable _start.
34
- * @returns The start value, which is of type number.
64
+ * Create a sum segment tree.
65
+ * @example
66
+ * ```ts
67
+ * const st = SegmentTree.sum([1, 2, 3, 4, 5]);
68
+ * st.query(0, 2); // 6 (1+2+3)
69
+ * st.update(1, 10);
70
+ * st.query(0, 2); // 14 (1+10+3)
71
+ * ```
35
72
  */
36
- get start(): number {
37
- return this._start;
73
+ static sum(elements: number[]): SegmentTree<number> {
74
+ return new SegmentTree<number>(elements, {
75
+ merger: (a, b) => a + b,
76
+ identity: 0
77
+ });
38
78
  }
39
79
 
40
80
  /**
41
- * The above function sets the value of the "start" property.
42
- * @param {number} value - The value parameter is of type number.
81
+ * Create a min segment tree.
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+ * @example
94
+ * // Temperature monitoring with range queries
95
+ * // Hourly temperatures for a day (24 readings)
96
+ * const temps = [18, 17, 16, 15, 16, 18, 21, 24, 27, 29, 31, 32, 33, 32, 31, 29, 27, 25, 23, 21, 20, 19, 18, 17];
97
+ * const tree = SegmentTree.sum(temps);
98
+ *
99
+ * // Average temperature during work hours (9-17)
100
+ * const workSum = tree.query(9, 17);
101
+ * console.log(workSum / 9); // toBeCloseTo;
102
+ *
103
+ * // Sum of morning temps (6-11)
104
+ * console.log(tree.query(6, 11)); // 164;
43
105
  */
44
- set start(value: number) {
45
- this._start = value;
106
+ static min(elements: number[]): SegmentTree<number> {
107
+ return new SegmentTree<number>(elements, {
108
+ merger: (a, b) => Math.min(a, b),
109
+ identity: Infinity
110
+ });
46
111
  }
47
112
 
48
- protected _end = 0;
49
-
50
113
  /**
51
- * The function returns the value of the protected variable `_end`.
52
- * @returns The value of the protected property `_end`.
114
+ * Create a max segment tree.
115
+ * @example
116
+ * ```ts
117
+ * const st = SegmentTree.max([3, 1, 4, 1, 5]);
118
+ * st.query(1, 4); // 5
119
+ * ```
53
120
  */
54
- get end(): number {
55
- return this._end;
121
+ static max(elements: number[]): SegmentTree<number> {
122
+ return new SegmentTree<number>(elements, {
123
+ merger: (a, b) => Math.max(a, b),
124
+ identity: -Infinity
125
+ });
56
126
  }
57
127
 
128
+ // ─── Core operations ───────────────────────────────────────
129
+
58
130
  /**
59
- * The above function sets the value of the "end" property.
60
- * @param {number} value - The value parameter is a number that represents the new value for the end
61
- * property.
131
+ * Point update: set element at index to value.
132
+ * Time: O(log n)
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+ * @example
145
+ * // Dynamic range sum with updates
146
+ * // Monthly revenue data (in thousands)
147
+ * const revenue = [120, 95, 140, 110, 85, 130, 150, 100, 160, 125, 90, 175];
148
+ * const tree = SegmentTree.sum(revenue);
149
+ *
150
+ * // Q1 revenue (Jan-Mar)
151
+ * console.log(tree.query(0, 2)); // 355;
152
+ *
153
+ * // Update March revenue from 140 to 200
154
+ * tree.update(2, 200);
155
+ *
156
+ * // Q1 revenue after update
157
+ * console.log(tree.query(0, 2)); // 415;
158
+ *
159
+ * // H1 revenue (Jan-Jun)
160
+ * console.log(tree.query(0, 5)); // 740;
62
161
  */
63
- set end(value: number) {
64
- this._end = value;
65
- }
162
+ update(index: number, value: E): void {
163
+ if (index < 0 || index >= this._n) return;
66
164
 
67
- protected _value: SegmentTreeNodeVal | undefined = undefined;
165
+ let pos = this._treeSize + index;
166
+ this._tree[pos] = value;
68
167
 
69
- /**
70
- * The function returns the value of a segment tree node.
71
- * @returns The value being returned is either a `SegmentTreeNodeVal` object or `undefined`.
72
- */
73
- get value(): SegmentTreeNodeVal | undefined {
74
- return this._value;
168
+ // Propagate up
169
+ pos >>= 1;
170
+ while (pos >= 1) {
171
+ this._tree[pos] = this._merger(this._tree[2 * pos], this._tree[2 * pos + 1]);
172
+ pos >>= 1;
173
+ }
75
174
  }
76
175
 
77
176
  /**
78
- * The function sets the value of a segment tree node.
79
- * @param {SegmentTreeNodeVal | undefined} value - The `value` parameter is of type
80
- * `SegmentTreeNodeVal` or `undefined`.
177
+ * Range query: returns merger result over [start, end] (inclusive).
178
+ * Time: O(log n)
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+ * @example
191
+ * // Range sum query on an array
192
+ * const tree = SegmentTree.sum([1, 3, 5, 7, 9, 11]);
193
+ *
194
+ * // Query sum of range [1, 3] → 3 + 5 + 7 = 15
195
+ * console.log(tree.query(1, 3)); // 15;
196
+ *
197
+ * // Query entire range
198
+ * console.log(tree.query(0, 5)); // 36;
199
+ *
200
+ * // Query single element
201
+ * console.log(tree.query(2, 2)); // 5;
81
202
  */
82
- set value(value: SegmentTreeNodeVal | undefined) {
83
- this._value = value;
84
- }
85
-
86
- protected _sum = 0;
203
+ query(start: number, end: number): E {
204
+ if (start < 0) start = 0;
205
+ if (end >= this._n) end = this._n - 1;
206
+ if (start > end) return this._identity;
207
+
208
+ let resultLeft = this._identity;
209
+ let resultRight = this._identity;
210
+ let left = this._treeSize + start;
211
+ let right = this._treeSize + end + 1; // exclusive
212
+
213
+ while (left < right) {
214
+ if (left & 1) {
215
+ resultLeft = this._merger(resultLeft, this._tree[left]);
216
+ left++;
217
+ }
218
+ if (right & 1) {
219
+ right--;
220
+ resultRight = this._merger(this._tree[right], resultRight);
221
+ }
222
+ left >>= 1;
223
+ right >>= 1;
224
+ }
87
225
 
88
- /**
89
- * The function returns the value of the sum property.
90
- * @returns The method is returning the value of the variable `_sum`.
91
- */
92
- get sum(): number {
93
- return this._sum;
226
+ return this._merger(resultLeft, resultRight);
94
227
  }
95
228
 
96
229
  /**
97
- * The above function sets the value of the sum property.
98
- * @param {number} value - The parameter "value" is of type "number".
230
+ * Get element at index.
231
+ * Time: O(1)
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+ * @example
244
+ * // Point access on segment tree
245
+ * const st = SegmentTree.sum([10, 20, 30, 40]);
246
+ * console.log(st.get(0)); // 10;
247
+ * console.log(st.get(2)); // 30;
99
248
  */
100
- set sum(value: number) {
101
- this._sum = value;
249
+ get(index: number): E {
250
+ if (index < 0 || index >= this._n) return this._identity;
251
+ return this._tree[this._treeSize + index];
102
252
  }
103
253
 
104
- protected _left: SegmentTreeNode | undefined = undefined;
254
+ // ─── Binary search on tree (ACL-style) ─────────────────────
105
255
 
106
256
  /**
107
- * The function returns the left child of a segment tree node.
108
- * @returns The `left` property of the `SegmentTreeNode` object is being returned. It is of type
109
- * `SegmentTreeNode` or `undefined`.
257
+ * Find the largest r such that predicate(query(left, r)) is true.
258
+ * Returns left-1 if predicate(identity) is false.
259
+ * Returns n-1 if predicate holds for the entire range [left, n-1].
260
+ * Time: O(log n)
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+ * @example
273
+ * // Find rightmost position where predicate holds
274
+ * // Prefix sums: find the rightmost index where prefix sum < 10
275
+ * const st = SegmentTree.sum([3, 1, 4, 1, 5]);
276
+ * // maxRight(0, sum => sum < 10) — prefix [3,4,8,9,14]
277
+ * // sum < 10 holds through index 3 (prefix=9), fails at 4 (prefix=14)
278
+ * const result = st.maxRight(0, sum => sum < 10);
279
+ * console.log(result); // 3;
110
280
  */
111
- get left(): SegmentTreeNode | undefined {
112
- return this._left;
113
- }
281
+ maxRight(left: number, predicate: (segValue: E) => boolean): number {
282
+ if (left >= this._n) return this._n - 1;
283
+
284
+ let acc = this._identity;
285
+ if (!predicate(acc)) return left - 1;
286
+
287
+ let pos = this._treeSize + left;
288
+
289
+ // Go up while we're a right child or predicate still holds
290
+ while (true) {
291
+ // Find the lowest relevant node
292
+ while (pos < this._treeSize) {
293
+ // Try going left
294
+ const combined = this._merger(acc, this._tree[2 * pos]);
295
+ if (predicate(combined)) {
296
+ acc = combined;
297
+ pos = 2 * pos + 1; // go right
298
+ } else {
299
+ pos = 2 * pos; // go left (dig deeper)
300
+ }
301
+ }
114
302
 
115
- /**
116
- * The function sets the value of the left property of a SegmentTreeNode object.
117
- * @param {SegmentTreeNode | undefined} value - The value parameter is of type SegmentTreeNode or
118
- * undefined.
119
- */
120
- set left(value: SegmentTreeNode | undefined) {
121
- this._left = value;
122
- }
303
+ // At leaf level
304
+ const combined = this._merger(acc, this._tree[pos]);
305
+ if (!predicate(combined)) {
306
+ return pos - this._treeSize - 1;
307
+ }
308
+ acc = combined;
123
309
 
124
- protected _right: SegmentTreeNode | undefined = undefined;
310
+ // Move to next segment
311
+ pos++;
312
+ // Check if we've gone past the end
313
+ if (pos - this._treeSize >= this._n) return this._n - 1;
125
314
 
126
- /**
127
- * The function returns the right child of a segment tree node.
128
- * @returns The `getRight()` method is returning a value of type `SegmentTreeNode` or `undefined`.
129
- */
130
- get right(): SegmentTreeNode | undefined {
131
- return this._right;
315
+ // Go up while we're a right child
316
+ while (pos > 1 && (pos & 1) === 0) {
317
+ pos >>= 1;
318
+ }
319
+ /* istanbul ignore next -- defensive: pos===1 unreachable when _n < _treeSize guard above catches exit */
320
+ if (pos === 1) return this._n - 1;
321
+ }
132
322
  }
133
323
 
134
324
  /**
135
- * The function sets the right child of a segment tree node.
136
- * @param {SegmentTreeNode | undefined} value - The `value` parameter is of type `SegmentTreeNode |
137
- * undefined`. This means that it can accept either a `SegmentTreeNode` object or `undefined` as its
138
- * value.
325
+ * Find the smallest l such that predicate(query(l, right)) is true.
326
+ * Returns right+1 if predicate(identity) is false.
327
+ * Returns 0 if predicate holds for the entire range [0, right].
328
+ * Time: O(log n)
329
+
330
+
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+ * @example
341
+ * // Find leftmost position where predicate holds
342
+ * const st = SegmentTree.sum([3, 1, 4, 1, 5]);
343
+ * // minLeft(5, sum => sum < 7) — suffix sums from right
344
+ * // From right: [5]=5 < 7, [1,5]=6 < 7, [4,1,5]=10 ≥ 7
345
+ * const result = st.minLeft(5, sum => sum < 7);
346
+ * console.log(result); // 3;
139
347
  */
140
- set right(value: SegmentTreeNode | undefined) {
141
- this._right = value;
142
- }
143
- }
348
+ minLeft(right: number, predicate: (segValue: E) => boolean): number {
349
+ if (right < 0) return 0;
350
+ if (right >= this._n) right = this._n - 1;
144
351
 
145
- export class SegmentTree {
146
- /**
147
- * The constructor initializes the values, start, end, and root properties of an object.
148
- * @param {number[]} values - An array of numbers that will be used to build a binary search tree.
149
- * @param {number} [start] - The `start` parameter is the index of the first element in the `values` array that should
150
- * be included in the range. If no value is provided for `start`, it defaults to 0, which means the range starts from
151
- * the beginning of the array.
152
- * @param {number} [end] - The "end" parameter is the index of the last element in the "values" array that should be
153
- * included in the range. If not provided, it defaults to the index of the last element in the "values" array.
154
- */
155
- constructor(values: number[], start?: number, end?: number) {
156
- start = start || 0;
157
- end = end || values.length - 1;
158
- this._values = values;
159
- this._start = start;
160
- this._end = end;
161
-
162
- if (values.length > 0) {
163
- this._root = this.build(start, end);
164
- } else {
165
- this._root = undefined;
166
- this._values = [];
167
- }
168
- }
352
+ let acc = this._identity;
353
+ if (!predicate(acc)) return right + 1;
169
354
 
170
- protected _values: number[] = [];
355
+ let pos = this._treeSize + right;
171
356
 
172
- /**
173
- * The function returns an array of numbers.
174
- * @returns An array of numbers is being returned.
175
- */
176
- get values(): number[] {
177
- return this._values;
178
- }
357
+ while (true) {
358
+ while (pos < this._treeSize) {
359
+ const combined = this._merger(this._tree[2 * pos + 1], acc);
360
+ if (predicate(combined)) {
361
+ acc = combined;
362
+ pos = 2 * pos; // go left
363
+ } else {
364
+ pos = 2 * pos + 1; // go right (dig deeper)
365
+ }
366
+ }
179
367
 
180
- protected _start = 0;
368
+ const combined = this._merger(this._tree[pos], acc);
369
+ if (!predicate(combined)) {
370
+ return pos - this._treeSize + 1;
371
+ }
372
+ acc = combined;
181
373
 
182
- /**
183
- * The function returns the value of the protected variable _start.
184
- * @returns The start value, which is of type number.
185
- */
186
- get start(): number {
187
- return this._start;
374
+ // Move to previous segment
375
+ if (pos === this._treeSize) return 0;
376
+ pos--;
377
+
378
+ // Go up while we're a left child
379
+ while (pos > 1 && (pos & 1) === 1) {
380
+ pos >>= 1;
381
+ }
382
+ /* istanbul ignore next -- defensive: pos===1 unreachable when _treeSize guard above catches exit */
383
+ if (pos === 1) return 0;
384
+ }
188
385
  }
189
386
 
190
- protected _end: number;
387
+ // ─── Standard interface ────────────────────────────────────
191
388
 
192
- /**
193
- * The function returns the value of the protected variable `_end`.
194
- * @returns The value of the protected property `_end`.
195
- */
196
- get end(): number {
197
- return this._end;
389
+ get size(): number {
390
+ return this._n;
198
391
  }
199
392
 
200
- protected _root: SegmentTreeNode | undefined;
393
+ isEmpty(): boolean {
394
+ return this._n === 0;
395
+ }
201
396
 
202
- /**
203
- * The function returns the root node of a segment tree.
204
- * @returns The `root` property of the class `SegmentTreeNode` or `undefined` if it is not defined.
205
- */
206
- get root(): SegmentTreeNode | undefined {
207
- return this._root;
397
+ clone(): SegmentTree<E> {
398
+ const elements: E[] = [];
399
+ for (let i = 0; i < this._n; i++) {
400
+ elements.push(this._tree[this._treeSize + i]);
401
+ }
402
+ return new SegmentTree<E>(elements, {
403
+ merger: this._merger,
404
+ identity: this._identity
405
+ });
208
406
  }
209
407
 
210
- /**
211
- * The build function creates a segment tree by recursively dividing the given range into smaller segments and assigning
212
- * the sum of values to each segment.
213
- * @param {number} start - The `start` parameter represents the starting index of the segment or range for which we are
214
- * building the segment tree.
215
- * @param {number} end - The "end" parameter represents the ending index of the segment or range for which we want to
216
- * build a segment tree.
217
- * @returns a SegmentTreeNode object.
218
- */
219
- build(start: number, end: number): SegmentTreeNode {
220
- if (start > end) {
221
- return new SegmentTreeNode(start, end, 0);
408
+ toArray(): E[] {
409
+ const result: E[] = [];
410
+ for (let i = 0; i < this._n; i++) {
411
+ result.push(this._tree[this._treeSize + i]);
222
412
  }
223
- if (start === end) return new SegmentTreeNode(start, end, this._values[start]);
224
-
225
- const mid = start + Math.floor((end - start) / 2);
226
- const left = this.build(start, mid);
227
- const right = this.build(mid + 1, end);
228
- const cur = new SegmentTreeNode(start, end, left.sum + right.sum);
229
- cur.left = left;
230
- cur.right = right;
231
- return cur;
413
+ return result;
232
414
  }
233
415
 
234
416
  /**
235
- * The function updates the value of a node in a segment tree and recalculates the sum of its children if they exist.
236
- * @param {number} index - The index parameter represents the index of the node in the segment tree that needs to be
237
- * updated.
238
- * @param {number} sum - The `sum` parameter represents the new value that should be assigned to the `sum` property of
239
- * the `SegmentTreeNode` at the specified `index`.
240
- * @param {SegmentTreeNodeVal} [value] - The `value` parameter is an optional value that can be assigned to the `value`
241
- * property of the `SegmentTreeNode` object. It is not currently used in the code, but you can uncomment the line `//
242
- * cur.value = value;` and pass a value for `value` in the
243
- * @returns The function does not return anything.
417
+ * Iterates over leaf values in index order.
244
418
  */
245
- updateNode(index: number, sum: number, value?: SegmentTreeNodeVal) {
246
- const root = this.root || undefined;
247
- if (!root) {
248
- return;
249
- }
250
- const dfs = (cur: SegmentTreeNode, index: number, sum: number, value?: SegmentTreeNodeVal) => {
251
- if (cur.start === cur.end && cur.start === index) {
252
- cur.sum = sum;
253
- if (value !== undefined) cur.value = value;
254
- return;
255
- }
256
- const mid = cur.start + Math.floor((cur.end - cur.start) / 2);
257
- if (index <= mid) {
258
- if (cur.left) {
259
- dfs(cur.left, index, sum, value);
419
+ [Symbol.iterator](): IterableIterator<E> {
420
+ const tree = this._tree;
421
+ const treeSize = this._treeSize;
422
+ const n = this._n;
423
+ let i = 0;
424
+ return {
425
+ [Symbol.iterator]() {
426
+ return this;
427
+ },
428
+ next(): IteratorResult<E> {
429
+ if (i < n) {
430
+ return { value: tree[treeSize + i++], done: false };
260
431
  }
261
- } else {
262
- if (cur.right) {
263
- dfs(cur.right, index, sum, value);
264
- }
265
- }
266
- if (cur.left && cur.right) {
267
- cur.sum = cur.left.sum + cur.right.sum;
432
+ return { value: undefined as any, done: true };
268
433
  }
269
434
  };
270
-
271
- dfs(root, index, sum, value);
272
435
  }
273
436
 
274
- /**
275
- * The function `querySumByRange` calculates the sum of values within a given range in a segment tree.
276
- * @param {number} indexA - The starting index of the range for which you want to calculate the sum.
277
- * @param {number} indexB - The parameter `indexB` represents the ending index of the range for which you want to
278
- * calculate the sum.
279
- * @returns The function `querySumByRange` returns a number.
280
- */
281
- querySumByRange(indexA: number, indexB: number): number {
282
- const root = this.root || undefined;
283
- if (!root) {
284
- return 0;
285
- }
286
-
287
- if (indexA < 0 || indexB >= this.values.length || indexA > indexB) {
288
- return NaN;
437
+ forEach(callback: (value: E, index: number) => void): void {
438
+ for (let i = 0; i < this._n; i++) {
439
+ callback(this._tree[this._treeSize + i], i);
289
440
  }
441
+ }
290
442
 
291
- const dfs = (cur: SegmentTreeNode, i: number, j: number): number => {
292
- if (i <= cur.start && j >= cur.end) {
293
- // The range [i, j] completely covers the current node's range [cur.start, cur.end]
294
- return cur.sum;
295
- }
296
- const mid = cur.start + Math.floor((cur.end - cur.start) / 2);
297
- if (j <= mid) {
298
- if (cur.left) {
299
- return dfs(cur.left, i, j);
300
- } else {
301
- return NaN;
302
- }
303
- } else if (i > mid) {
304
- if (cur.right) {
305
- return dfs(cur.right, i, j);
306
- } else {
307
- return NaN;
308
- }
309
- } else {
310
- // Query both left and right subtrees
311
- let leftSum = 0;
312
- let rightSum = 0;
313
- if (cur.left) {
314
- leftSum = dfs(cur.left, i, mid);
315
- }
316
- if (cur.right) {
317
- rightSum = dfs(cur.right, mid + 1, j);
318
- }
319
- return leftSum + rightSum;
320
- }
321
- };
322
- return dfs(root, indexA, indexB);
443
+ print(): void {
444
+ console.log(this.toArray());
323
445
  }
324
446
  }
447
+
448
+