data-structure-typed 2.4.5 → 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 (71) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +15 -5
  3. package/dist/cjs/index.cjs +10240 -2079
  4. package/dist/cjs-legacy/index.cjs +10305 -2135
  5. package/dist/esm/index.mjs +10241 -2078
  6. package/dist/esm-legacy/index.mjs +10306 -2134
  7. package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
  8. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +128 -51
  9. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +210 -164
  10. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +429 -78
  11. package/dist/types/data-structures/binary-tree/bst.d.ts +311 -28
  12. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +212 -32
  13. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +218 -152
  14. package/dist/types/data-structures/binary-tree/tree-map.d.ts +1281 -5
  15. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +1087 -201
  16. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +858 -65
  17. package/dist/types/data-structures/binary-tree/tree-set.d.ts +1133 -5
  18. package/dist/types/data-structures/graph/directed-graph.d.ts +219 -47
  19. package/dist/types/data-structures/graph/map-graph.d.ts +59 -1
  20. package/dist/types/data-structures/graph/undirected-graph.d.ts +204 -59
  21. package/dist/types/data-structures/hash/hash-map.d.ts +230 -77
  22. package/dist/types/data-structures/heap/heap.d.ts +287 -99
  23. package/dist/types/data-structures/heap/max-heap.d.ts +46 -0
  24. package/dist/types/data-structures/heap/min-heap.d.ts +59 -0
  25. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +286 -44
  26. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +278 -65
  27. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +415 -12
  28. package/dist/types/data-structures/matrix/matrix.d.ts +331 -0
  29. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +57 -0
  30. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +60 -0
  31. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +60 -0
  32. package/dist/types/data-structures/queue/deque.d.ts +272 -65
  33. package/dist/types/data-structures/queue/queue.d.ts +211 -42
  34. package/dist/types/data-structures/stack/stack.d.ts +174 -32
  35. package/dist/types/data-structures/trie/trie.d.ts +213 -43
  36. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -1
  37. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +1 -4
  38. package/dist/umd/data-structure-typed.js +10308 -2133
  39. package/dist/umd/data-structure-typed.min.js +4 -4
  40. package/package.json +5 -4
  41. package/src/data-structures/base/iterable-element-base.ts +4 -5
  42. package/src/data-structures/binary-tree/avl-tree.ts +146 -51
  43. package/src/data-structures/binary-tree/binary-indexed-tree.ts +316 -247
  44. package/src/data-structures/binary-tree/binary-tree.ts +454 -79
  45. package/src/data-structures/binary-tree/bst.ts +359 -34
  46. package/src/data-structures/binary-tree/red-black-tree.ts +309 -97
  47. package/src/data-structures/binary-tree/segment-tree.ts +378 -248
  48. package/src/data-structures/binary-tree/tree-map.ts +1403 -6
  49. package/src/data-structures/binary-tree/tree-multi-map.ts +1214 -211
  50. package/src/data-structures/binary-tree/tree-multi-set.ts +954 -65
  51. package/src/data-structures/binary-tree/tree-set.ts +1250 -9
  52. package/src/data-structures/graph/directed-graph.ts +229 -47
  53. package/src/data-structures/graph/map-graph.ts +59 -1
  54. package/src/data-structures/graph/undirected-graph.ts +213 -59
  55. package/src/data-structures/hash/hash-map.ts +241 -77
  56. package/src/data-structures/heap/heap.ts +301 -99
  57. package/src/data-structures/heap/max-heap.ts +46 -0
  58. package/src/data-structures/heap/min-heap.ts +59 -0
  59. package/src/data-structures/linked-list/doubly-linked-list.ts +303 -44
  60. package/src/data-structures/linked-list/singly-linked-list.ts +293 -65
  61. package/src/data-structures/linked-list/skip-linked-list.ts +707 -90
  62. package/src/data-structures/matrix/matrix.ts +424 -12
  63. package/src/data-structures/priority-queue/max-priority-queue.ts +57 -0
  64. package/src/data-structures/priority-queue/min-priority-queue.ts +60 -0
  65. package/src/data-structures/priority-queue/priority-queue.ts +60 -0
  66. package/src/data-structures/queue/deque.ts +287 -65
  67. package/src/data-structures/queue/queue.ts +223 -42
  68. package/src/data-structures/stack/stack.ts +184 -32
  69. package/src/data-structures/trie/trie.ts +225 -43
  70. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -1
  71. package/src/types/data-structures/linked-list/skip-linked-list.ts +2 -1
@@ -6,319 +6,449 @@
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
+
94
+ * @example
95
+ * // Temperature monitoring with range queries
96
+ * // Hourly temperatures for a day (24 readings)
97
+ * 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];
98
+ * const tree = SegmentTree.sum(temps);
99
+ *
100
+ * // Average temperature during work hours (9-17)
101
+ * const workSum = tree.query(9, 17);
102
+ * console.log(workSum / 9); // toBeCloseTo;
103
+ *
104
+ * // Sum of morning temps (6-11)
105
+ * console.log(tree.query(6, 11)); // 164;
43
106
  */
44
- set start(value: number) {
45
- this._start = value;
107
+ static min(elements: number[]): SegmentTree<number> {
108
+ return new SegmentTree<number>(elements, {
109
+ merger: (a, b) => Math.min(a, b),
110
+ identity: Infinity
111
+ });
46
112
  }
47
113
 
48
- protected _end = 0;
49
-
50
114
  /**
51
- * The function returns the value of the protected variable `_end`.
52
- * @returns The value of the protected property `_end`.
115
+ * Create a max segment tree.
116
+ * @example
117
+ * ```ts
118
+ * const st = SegmentTree.max([3, 1, 4, 1, 5]);
119
+ * st.query(1, 4); // 5
120
+ * ```
53
121
  */
54
- get end(): number {
55
- return this._end;
122
+ static max(elements: number[]): SegmentTree<number> {
123
+ return new SegmentTree<number>(elements, {
124
+ merger: (a, b) => Math.max(a, b),
125
+ identity: -Infinity
126
+ });
56
127
  }
57
128
 
129
+ // ─── Core operations ───────────────────────────────────────
130
+
58
131
  /**
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.
132
+ * Point update: set element at index to value.
133
+ * Time: O(log n)
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+ * @example
147
+ * // Dynamic range sum with updates
148
+ * // Monthly revenue data (in thousands)
149
+ * const revenue = [120, 95, 140, 110, 85, 130, 150, 100, 160, 125, 90, 175];
150
+ * const tree = SegmentTree.sum(revenue);
151
+ *
152
+ * // Q1 revenue (Jan-Mar)
153
+ * console.log(tree.query(0, 2)); // 355;
154
+ *
155
+ * // Update March revenue from 140 to 200
156
+ * tree.update(2, 200);
157
+ *
158
+ * // Q1 revenue after update
159
+ * console.log(tree.query(0, 2)); // 415;
160
+ *
161
+ * // H1 revenue (Jan-Jun)
162
+ * console.log(tree.query(0, 5)); // 740;
62
163
  */
63
- set end(value: number) {
64
- this._end = value;
65
- }
164
+ update(index: number, value: E): void {
165
+ if (index < 0 || index >= this._n) return;
66
166
 
67
- protected _value: SegmentTreeNodeVal | undefined = undefined;
167
+ let pos = this._treeSize + index;
168
+ this._tree[pos] = value;
68
169
 
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;
170
+ // Propagate up
171
+ pos >>= 1;
172
+ while (pos >= 1) {
173
+ this._tree[pos] = this._merger(this._tree[2 * pos], this._tree[2 * pos + 1]);
174
+ pos >>= 1;
175
+ }
75
176
  }
76
177
 
77
178
  /**
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`.
179
+ * Range query: returns merger result over [start, end] (inclusive).
180
+ * Time: O(log n)
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+ * @example
194
+ * // Range sum query on an array
195
+ * const tree = SegmentTree.sum([1, 3, 5, 7, 9, 11]);
196
+ *
197
+ * // Query sum of range [1, 3] → 3 + 5 + 7 = 15
198
+ * console.log(tree.query(1, 3)); // 15;
199
+ *
200
+ * // Query entire range
201
+ * console.log(tree.query(0, 5)); // 36;
202
+ *
203
+ * // Query single element
204
+ * console.log(tree.query(2, 2)); // 5;
81
205
  */
82
- set value(value: SegmentTreeNodeVal | undefined) {
83
- this._value = value;
84
- }
85
-
86
- protected _sum = 0;
206
+ query(start: number, end: number): E {
207
+ if (start < 0) start = 0;
208
+ if (end >= this._n) end = this._n - 1;
209
+ if (start > end) return this._identity;
210
+
211
+ let resultLeft = this._identity;
212
+ let resultRight = this._identity;
213
+ let left = this._treeSize + start;
214
+ let right = this._treeSize + end + 1; // exclusive
215
+
216
+ while (left < right) {
217
+ if (left & 1) {
218
+ resultLeft = this._merger(resultLeft, this._tree[left]);
219
+ left++;
220
+ }
221
+ if (right & 1) {
222
+ right--;
223
+ resultRight = this._merger(this._tree[right], resultRight);
224
+ }
225
+ left >>= 1;
226
+ right >>= 1;
227
+ }
87
228
 
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;
229
+ return this._merger(resultLeft, resultRight);
94
230
  }
95
231
 
96
232
  /**
97
- * The above function sets the value of the sum property.
98
- * @param {number} value - The parameter "value" is of type "number".
233
+ * Get element at index.
234
+ * Time: O(1)
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+ * @example
248
+ * // Point access on segment tree
249
+ * const st = SegmentTree.sum([10, 20, 30, 40]);
250
+ * console.log(st.get(0)); // 10;
251
+ * console.log(st.get(2)); // 30;
99
252
  */
100
- set sum(value: number) {
101
- this._sum = value;
253
+ get(index: number): E {
254
+ if (index < 0 || index >= this._n) return this._identity;
255
+ return this._tree[this._treeSize + index];
102
256
  }
103
257
 
104
- protected _left: SegmentTreeNode | undefined = undefined;
258
+ // ─── Binary search on tree (ACL-style) ─────────────────────
105
259
 
106
260
  /**
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`.
261
+ * Find the largest r such that predicate(query(left, r)) is true.
262
+ * Returns left-1 if predicate(identity) is false.
263
+ * Returns n-1 if predicate holds for the entire range [left, n-1].
264
+ * Time: O(log n)
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+
273
+
274
+
275
+
276
+
277
+ * @example
278
+ * // Find rightmost position where predicate holds
279
+ * // Prefix sums: find the rightmost index where prefix sum < 10
280
+ * const st = SegmentTree.sum([3, 1, 4, 1, 5]);
281
+ * // maxRight(0, sum => sum < 10) — prefix [3,4,8,9,14]
282
+ * // sum < 10 holds through index 3 (prefix=9), fails at 4 (prefix=14)
283
+ * const result = st.maxRight(0, sum => sum < 10);
284
+ * console.log(result); // 3;
110
285
  */
111
- get left(): SegmentTreeNode | undefined {
112
- return this._left;
113
- }
286
+ maxRight(left: number, predicate: (segValue: E) => boolean): number {
287
+ if (left >= this._n) return this._n - 1;
288
+
289
+ let acc = this._identity;
290
+ if (!predicate(acc)) return left - 1;
291
+
292
+ let pos = this._treeSize + left;
293
+
294
+ // Go up while we're a right child or predicate still holds
295
+ while (true) {
296
+ // Find the lowest relevant node
297
+ while (pos < this._treeSize) {
298
+ // Try going left
299
+ const combined = this._merger(acc, this._tree[2 * pos]);
300
+ if (predicate(combined)) {
301
+ acc = combined;
302
+ pos = 2 * pos + 1; // go right
303
+ } else {
304
+ pos = 2 * pos; // go left (dig deeper)
305
+ }
306
+ }
114
307
 
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
- }
308
+ // At leaf level
309
+ const combined = this._merger(acc, this._tree[pos]);
310
+ if (!predicate(combined)) {
311
+ return pos - this._treeSize - 1;
312
+ }
313
+ acc = combined;
123
314
 
124
- protected _right: SegmentTreeNode | undefined = undefined;
315
+ // Move to next segment
316
+ pos++;
317
+ // Check if we've gone past the end
318
+ if (pos - this._treeSize >= this._n) return this._n - 1;
125
319
 
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;
320
+ // Go up while we're a right child
321
+ while (pos > 1 && (pos & 1) === 0) {
322
+ pos >>= 1;
323
+ }
324
+ /* istanbul ignore next -- defensive: pos===1 unreachable when _n < _treeSize guard above catches exit */
325
+ if (pos === 1) return this._n - 1;
326
+ }
132
327
  }
133
328
 
134
329
  /**
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.
330
+ * Find the smallest l such that predicate(query(l, right)) is true.
331
+ * Returns right+1 if predicate(identity) is false.
332
+ * Returns 0 if predicate holds for the entire range [0, right].
333
+ * Time: O(log n)
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+
346
+ * @example
347
+ * // Find leftmost position where predicate holds
348
+ * const st = SegmentTree.sum([3, 1, 4, 1, 5]);
349
+ * // minLeft(5, sum => sum < 7) — suffix sums from right
350
+ * // From right: [5]=5 < 7, [1,5]=6 < 7, [4,1,5]=10 ≥ 7
351
+ * const result = st.minLeft(5, sum => sum < 7);
352
+ * console.log(result); // 3;
139
353
  */
140
- set right(value: SegmentTreeNode | undefined) {
141
- this._right = value;
142
- }
143
- }
354
+ minLeft(right: number, predicate: (segValue: E) => boolean): number {
355
+ if (right < 0) return 0;
356
+ if (right >= this._n) right = this._n - 1;
144
357
 
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
- }
358
+ let acc = this._identity;
359
+ if (!predicate(acc)) return right + 1;
169
360
 
170
- protected _values: number[] = [];
361
+ let pos = this._treeSize + right;
171
362
 
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
- }
363
+ while (true) {
364
+ while (pos < this._treeSize) {
365
+ const combined = this._merger(this._tree[2 * pos + 1], acc);
366
+ if (predicate(combined)) {
367
+ acc = combined;
368
+ pos = 2 * pos; // go left
369
+ } else {
370
+ pos = 2 * pos + 1; // go right (dig deeper)
371
+ }
372
+ }
179
373
 
180
- protected _start = 0;
374
+ const combined = this._merger(this._tree[pos], acc);
375
+ if (!predicate(combined)) {
376
+ return pos - this._treeSize + 1;
377
+ }
378
+ acc = combined;
181
379
 
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;
380
+ // Move to previous segment
381
+ if (pos === this._treeSize) return 0;
382
+ pos--;
383
+
384
+ // Go up while we're a left child
385
+ while (pos > 1 && (pos & 1) === 1) {
386
+ pos >>= 1;
387
+ }
388
+ /* istanbul ignore next -- defensive: pos===1 unreachable when _treeSize guard above catches exit */
389
+ if (pos === 1) return 0;
390
+ }
188
391
  }
189
392
 
190
- protected _end: number;
393
+ // ─── Standard interface ────────────────────────────────────
191
394
 
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;
395
+ get size(): number {
396
+ return this._n;
198
397
  }
199
398
 
200
- protected _root: SegmentTreeNode | undefined;
399
+ isEmpty(): boolean {
400
+ return this._n === 0;
401
+ }
201
402
 
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;
403
+ clone(): SegmentTree<E> {
404
+ const elements: E[] = [];
405
+ for (let i = 0; i < this._n; i++) {
406
+ elements.push(this._tree[this._treeSize + i]);
407
+ }
408
+ return new SegmentTree<E>(elements, {
409
+ merger: this._merger,
410
+ identity: this._identity
411
+ });
208
412
  }
209
413
 
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);
414
+ toArray(): E[] {
415
+ const result: E[] = [];
416
+ for (let i = 0; i < this._n; i++) {
417
+ result.push(this._tree[this._treeSize + i]);
222
418
  }
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;
419
+ return result;
232
420
  }
233
421
 
234
422
  /**
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.
423
+ * Iterates over leaf values in index order.
244
424
  */
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);
425
+ [Symbol.iterator](): IterableIterator<E> {
426
+ const tree = this._tree;
427
+ const treeSize = this._treeSize;
428
+ const n = this._n;
429
+ let i = 0;
430
+ return {
431
+ [Symbol.iterator]() {
432
+ return this;
433
+ },
434
+ next(): IteratorResult<E> {
435
+ if (i < n) {
436
+ return { value: tree[treeSize + i++], done: false };
260
437
  }
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;
438
+ return { value: undefined as any, done: true };
268
439
  }
269
440
  };
270
-
271
- dfs(root, index, sum, value);
272
441
  }
273
442
 
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;
443
+ forEach(callback: (value: E, index: number) => void): void {
444
+ for (let i = 0; i < this._n; i++) {
445
+ callback(this._tree[this._treeSize + i], i);
289
446
  }
447
+ }
290
448
 
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);
449
+ print(): void {
450
+ console.log(this.toArray());
323
451
  }
324
452
  }
453
+
454
+