min-heap-typed 1.50.2 → 1.50.4

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 (92) hide show
  1. package/dist/data-structures/base/iterable-base.d.ts +6 -0
  2. package/dist/data-structures/binary-tree/{tree-multimap.d.ts → avl-tree-multi-map.d.ts} +43 -10
  3. package/dist/data-structures/binary-tree/{tree-multimap.js → avl-tree-multi-map.js} +49 -11
  4. package/dist/data-structures/binary-tree/avl-tree.d.ts +29 -1
  5. package/dist/data-structures/binary-tree/avl-tree.js +33 -1
  6. package/dist/data-structures/binary-tree/binary-indexed-tree.d.ts +22 -0
  7. package/dist/data-structures/binary-tree/binary-indexed-tree.js +22 -0
  8. package/dist/data-structures/binary-tree/binary-tree.d.ts +1 -1
  9. package/dist/data-structures/binary-tree/binary-tree.js +1 -1
  10. package/dist/data-structures/binary-tree/bst.d.ts +46 -13
  11. package/dist/data-structures/binary-tree/bst.js +51 -20
  12. package/dist/data-structures/binary-tree/index.d.ts +2 -1
  13. package/dist/data-structures/binary-tree/index.js +2 -1
  14. package/dist/data-structures/binary-tree/rb-tree.d.ts +54 -2
  15. package/dist/data-structures/binary-tree/rb-tree.js +90 -24
  16. package/dist/data-structures/binary-tree/segment-tree.d.ts +99 -6
  17. package/dist/data-structures/binary-tree/segment-tree.js +127 -10
  18. package/dist/data-structures/binary-tree/tree-multi-map.d.ts +200 -0
  19. package/dist/data-structures/binary-tree/tree-multi-map.js +399 -0
  20. package/dist/data-structures/graph/abstract-graph.d.ts +0 -78
  21. package/dist/data-structures/graph/abstract-graph.js +0 -189
  22. package/dist/data-structures/graph/directed-graph.d.ts +59 -0
  23. package/dist/data-structures/graph/directed-graph.js +105 -0
  24. package/dist/data-structures/graph/undirected-graph.d.ts +60 -7
  25. package/dist/data-structures/graph/undirected-graph.js +126 -18
  26. package/dist/data-structures/hash/hash-map.d.ts +143 -23
  27. package/dist/data-structures/hash/hash-map.js +196 -62
  28. package/dist/data-structures/heap/heap.d.ts +29 -19
  29. package/dist/data-structures/heap/heap.js +29 -20
  30. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +71 -25
  31. package/dist/data-structures/linked-list/doubly-linked-list.js +83 -25
  32. package/dist/data-structures/linked-list/singly-linked-list.d.ts +26 -3
  33. package/dist/data-structures/linked-list/singly-linked-list.js +34 -3
  34. package/dist/data-structures/linked-list/skip-linked-list.d.ts +2 -2
  35. package/dist/data-structures/linked-list/skip-linked-list.js +2 -2
  36. package/dist/data-structures/matrix/matrix.d.ts +1 -1
  37. package/dist/data-structures/matrix/matrix.js +1 -1
  38. package/dist/data-structures/priority-queue/max-priority-queue.d.ts +10 -0
  39. package/dist/data-structures/priority-queue/max-priority-queue.js +10 -0
  40. package/dist/data-structures/priority-queue/min-priority-queue.d.ts +11 -0
  41. package/dist/data-structures/priority-queue/min-priority-queue.js +11 -0
  42. package/dist/data-structures/priority-queue/priority-queue.d.ts +8 -0
  43. package/dist/data-structures/priority-queue/priority-queue.js +8 -0
  44. package/dist/data-structures/queue/deque.d.ts +95 -21
  45. package/dist/data-structures/queue/deque.js +100 -16
  46. package/dist/data-structures/queue/queue.d.ts +65 -45
  47. package/dist/data-structures/queue/queue.js +65 -45
  48. package/dist/data-structures/stack/stack.d.ts +36 -22
  49. package/dist/data-structures/stack/stack.js +36 -22
  50. package/dist/data-structures/tree/tree.d.ts +57 -3
  51. package/dist/data-structures/tree/tree.js +77 -11
  52. package/dist/data-structures/trie/trie.d.ts +100 -36
  53. package/dist/data-structures/trie/trie.js +115 -36
  54. package/dist/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +5 -0
  55. package/dist/types/data-structures/binary-tree/index.d.ts +2 -1
  56. package/dist/types/data-structures/binary-tree/index.js +2 -1
  57. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +5 -0
  58. package/dist/types/data-structures/binary-tree/tree-multi-map.js +2 -0
  59. package/package.json +2 -2
  60. package/src/data-structures/base/iterable-base.ts +12 -0
  61. package/src/data-structures/binary-tree/{tree-multimap.ts → avl-tree-multi-map.ts} +59 -20
  62. package/src/data-structures/binary-tree/avl-tree.ts +37 -3
  63. package/src/data-structures/binary-tree/binary-indexed-tree.ts +22 -0
  64. package/src/data-structures/binary-tree/binary-tree.ts +1 -1
  65. package/src/data-structures/binary-tree/bst.ts +51 -19
  66. package/src/data-structures/binary-tree/index.ts +2 -1
  67. package/src/data-structures/binary-tree/rb-tree.ts +99 -28
  68. package/src/data-structures/binary-tree/segment-tree.ts +145 -11
  69. package/src/data-structures/binary-tree/tree-multi-map.ts +463 -0
  70. package/src/data-structures/graph/abstract-graph.ts +0 -211
  71. package/src/data-structures/graph/directed-graph.ts +122 -0
  72. package/src/data-structures/graph/undirected-graph.ts +143 -19
  73. package/src/data-structures/hash/hash-map.ts +228 -76
  74. package/src/data-structures/heap/heap.ts +31 -20
  75. package/src/data-structures/linked-list/doubly-linked-list.ts +96 -29
  76. package/src/data-structures/linked-list/singly-linked-list.ts +42 -6
  77. package/src/data-structures/linked-list/skip-linked-list.ts +2 -2
  78. package/src/data-structures/matrix/matrix.ts +1 -1
  79. package/src/data-structures/priority-queue/max-priority-queue.ts +10 -0
  80. package/src/data-structures/priority-queue/min-priority-queue.ts +11 -0
  81. package/src/data-structures/priority-queue/priority-queue.ts +8 -0
  82. package/src/data-structures/queue/deque.ts +118 -22
  83. package/src/data-structures/queue/queue.ts +68 -45
  84. package/src/data-structures/stack/stack.ts +39 -23
  85. package/src/data-structures/tree/tree.ts +89 -15
  86. package/src/data-structures/trie/trie.ts +131 -40
  87. package/src/types/data-structures/binary-tree/avl-tree-multi-map.ts +8 -0
  88. package/src/types/data-structures/binary-tree/index.ts +2 -1
  89. package/src/types/data-structures/binary-tree/tree-multi-map.ts +8 -0
  90. package/dist/types/data-structures/binary-tree/tree-multimap.d.ts +0 -5
  91. package/src/types/data-structures/binary-tree/tree-multimap.ts +0 -8
  92. /package/dist/types/data-structures/binary-tree/{tree-multimap.js → avl-tree-multi-map.js} +0 -0
@@ -0,0 +1,463 @@
1
+ /**
2
+ * data-structure-typed
3
+ *
4
+ * @author Tyler Zeng
5
+ * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
+ * @license MIT License
7
+ */
8
+ import type {
9
+ BinaryTreeDeleteResult,
10
+ BSTNKeyOrNode,
11
+ BTNCallback,
12
+ KeyOrNodeOrEntry,
13
+ TreeMultiMapNested,
14
+ TreeMultiMapNodeNested,
15
+ TreeMultiMapOptions
16
+ } from '../../types';
17
+ import { IterationType, RBTNColor } from '../../types';
18
+ import { IBinaryTree } from '../../interfaces';
19
+ import { RedBlackTree, RedBlackTreeNode } from './rb-tree';
20
+
21
+ export class TreeMultiMapNode<
22
+ K = any,
23
+ V = any,
24
+ NODE extends TreeMultiMapNode<K, V, NODE> = TreeMultiMapNodeNested<K, V>
25
+ > extends RedBlackTreeNode<K, V, NODE> {
26
+ /**
27
+ * The constructor function initializes an instance of a class with a key, value, and count.
28
+ * @param {K} key - The key parameter is of type K, which represents the type of the key for the
29
+ * constructor. It is required and must be provided when creating an instance of the class.
30
+ * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the
31
+ * value associated with the key in the constructor. If no value is provided, it will be `undefined`.
32
+ * @param [count=1] - The "count" parameter is an optional parameter that specifies the number of
33
+ * times the key-value pair should be repeated. If no value is provided for "count", it defaults to
34
+ * 1.
35
+ */
36
+ constructor(key: K, value?: V, count = 1) {
37
+ super(key, value);
38
+ this.count = count;
39
+ }
40
+
41
+ protected _count: number = 1;
42
+
43
+ /**
44
+ * The function returns the value of the private variable _count.
45
+ * @returns The count property of the object, which is of type number.
46
+ */
47
+ get count(): number {
48
+ return this._count;
49
+ }
50
+
51
+ /**
52
+ * The above function sets the value of the count property.
53
+ * @param {number} value - The value parameter is of type number, which means it can accept any
54
+ * numeric value.
55
+ */
56
+ set count(value: number) {
57
+ this._count = value;
58
+ }
59
+ }
60
+
61
+ export class TreeMultiMap<
62
+ K = any,
63
+ V = any,
64
+ NODE extends TreeMultiMapNode<K, V, NODE> = TreeMultiMapNode<K, V, TreeMultiMapNodeNested<K, V>>,
65
+ TREE extends TreeMultiMap<K, V, NODE, TREE> = TreeMultiMap<K, V, NODE, TreeMultiMapNested<K, V, NODE>>
66
+ >
67
+ extends RedBlackTree<K, V, NODE, TREE>
68
+ implements IBinaryTree<K, V, NODE, TREE> {
69
+ /**
70
+ * The constructor function initializes a new instance of the TreeMultiMap class with optional
71
+ * initial keys, nodes, or entries.
72
+ * @param keysOrNodesOrEntries - The `keysOrNodesOrEntries` parameter is an iterable object that can
73
+ * contain keys, nodes, or entries. It is used to initialize the TreeMultiMap with the provided keys,
74
+ * nodes, or entries.
75
+ * @param [options] - The `options` parameter is an optional object that can be passed to the
76
+ * constructor. It allows you to customize the behavior of the `TreeMultiMap` instance.
77
+ */
78
+ constructor(keysOrNodesOrEntries: Iterable<KeyOrNodeOrEntry<K, V, NODE>> = [], options?: TreeMultiMapOptions<K>) {
79
+ super([], options);
80
+ if (keysOrNodesOrEntries) this.addMany(keysOrNodesOrEntries);
81
+ }
82
+
83
+ protected _count = 0;
84
+
85
+ // TODO the _count is not accurate after nodes count modified
86
+ /**
87
+ * The function calculates the sum of the count property of all nodes in a tree structure.
88
+ * @returns the sum of the count property of all nodes in the tree.
89
+ */
90
+ get count(): number {
91
+ let sum = 0;
92
+ this.dfs(node => (sum += node.count));
93
+ return sum;
94
+ // return this._count;
95
+ }
96
+
97
+ /**
98
+ * The function creates a new TreeMultiMapNode object with the specified key, value, and count.
99
+ * @param {K} key - The key parameter represents the key of the node being created. It is of type K,
100
+ * which is a generic type that can be replaced with any specific type when using the function.
101
+ * @param {V} [value] - The `value` parameter is an optional parameter that represents the value
102
+ * associated with the key in the node. It is of type `V`, which can be any data type.
103
+ * @param {number} [count] - The `count` parameter represents the number of occurrences of a
104
+ * key-value pair in the TreeMultiMap. It is an optional parameter, so if it is not provided, it will
105
+ * default to 1.
106
+ * @returns a new instance of the TreeMultiMapNode class, casted as NODE.
107
+ */
108
+ override createNode(key: K, value?: V, count?: number): NODE {
109
+ return new TreeMultiMapNode(key, value, count) as NODE;
110
+ }
111
+
112
+ /**
113
+ * The function creates a new instance of a TreeMultiMap with the specified options and returns it.
114
+ * @param [options] - The `options` parameter is an optional object that contains additional
115
+ * configuration options for creating the `TreeMultiMap`. It can include properties such as
116
+ * `keyComparator`, `valueComparator`, `allowDuplicates`, etc.
117
+ * @returns a new instance of the `TreeMultiMap` class, with the provided options merged with the
118
+ * existing `iterationType` option. The returned value is casted as `TREE`.
119
+ */
120
+ override createTree(options?: TreeMultiMapOptions<K>): TREE {
121
+ return new TreeMultiMap<K, V, NODE, TREE>([], {
122
+ iterationType: this.iterationType,
123
+ ...options
124
+ }) as TREE;
125
+ }
126
+
127
+ /**
128
+ * The function `keyValueOrEntryToNode` takes a key, value, and count and returns a node if the input
129
+ * is valid.
130
+ * @param keyOrNodeOrEntry - The parameter `keyOrNodeOrEntry` can be of type `KeyOrNodeOrEntry<K, V,
131
+ * NODE>`. It can accept three types of values:
132
+ * @param {V} [value] - The `value` parameter is an optional value of type `V`. It represents the
133
+ * value associated with a key in a key-value pair.
134
+ * @param [count=1] - The count parameter is an optional parameter that specifies the number of times
135
+ * the key-value pair should be added to the node. If not provided, it defaults to 1.
136
+ * @returns a NODE object or undefined.
137
+ */
138
+ override keyValueOrEntryToNode(
139
+ keyOrNodeOrEntry: KeyOrNodeOrEntry<K, V, NODE>,
140
+ value?: V,
141
+ count = 1
142
+ ): NODE | undefined {
143
+ let node: NODE | undefined;
144
+ if (keyOrNodeOrEntry === undefined || keyOrNodeOrEntry === null) {
145
+ return;
146
+ } else if (this.isNode(keyOrNodeOrEntry)) {
147
+ node = keyOrNodeOrEntry;
148
+ } else if (this.isEntry(keyOrNodeOrEntry)) {
149
+ const [key, value] = keyOrNodeOrEntry;
150
+ if (key === undefined || key === null) {
151
+ return;
152
+ } else {
153
+ node = this.createNode(key, value, count);
154
+ }
155
+ } else if (!this.isNode(keyOrNodeOrEntry)) {
156
+ node = this.createNode(keyOrNodeOrEntry, value, count);
157
+ } else {
158
+ return;
159
+ }
160
+ return node;
161
+ }
162
+
163
+ /**
164
+ * The function "isNode" checks if a given key, node, or entry is an instance of the TreeMultiMapNode
165
+ * class.
166
+ * @param keyOrNodeOrEntry - The parameter `keyOrNodeOrEntry` can be of type `KeyOrNodeOrEntry<K, V,
167
+ * NODE>`.
168
+ * @returns a boolean value indicating whether the input parameter `keyOrNodeOrEntry` is an instance
169
+ * of the `TreeMultiMapNode` class.
170
+ */
171
+ override isNode(keyOrNodeOrEntry: KeyOrNodeOrEntry<K, V, NODE>): keyOrNodeOrEntry is NODE {
172
+ return keyOrNodeOrEntry instanceof TreeMultiMapNode;
173
+ }
174
+
175
+ /**
176
+ * Time Complexity: O(log n)
177
+ * Space Complexity: O(1)
178
+ */
179
+
180
+ /**
181
+ * Time Complexity: O(log n)
182
+ * Space Complexity: O(1)
183
+ *
184
+ * The function overrides the add method in TypeScript and adds a new node to the data structure.
185
+ * @param keyOrNodeOrEntry - The `keyOrNodeOrEntry` parameter can accept three types of values:
186
+ * @param {V} [value] - The `value` parameter represents the value associated with the key in the
187
+ * data structure.
188
+ * @param [count=1] - The `count` parameter represents the number of times the key-value pair should
189
+ * be added to the data structure. By default, it is set to 1, meaning that the key-value pair will
190
+ * be added once. However, you can specify a different value for `count` if you want to add
191
+ * @returns a boolean value.
192
+ */
193
+ override add(keyOrNodeOrEntry: KeyOrNodeOrEntry<K, V, NODE>, value?: V, count = 1): boolean {
194
+ const newNode = this.keyValueOrEntryToNode(keyOrNodeOrEntry, value, count);
195
+ if (newNode === undefined) return false;
196
+
197
+ const orgNodeCount = newNode?.count || 0;
198
+ const inserted = super.add(newNode);
199
+ if (inserted) {
200
+ this._count += orgNodeCount;
201
+ }
202
+ return true;
203
+ }
204
+
205
+ /**
206
+ * Time Complexity: O(log n)
207
+ * Space Complexity: O(1)
208
+ */
209
+
210
+ /**
211
+ * Time Complexity: O(log n)
212
+ * Space Complexity: O(1)
213
+ *
214
+ * The `delete` function in a TypeScript class is used to delete nodes from a binary tree based on a
215
+ * given identifier, and it returns an array of results containing information about the deleted
216
+ * nodes.
217
+ * @param {ReturnType<C> | null | undefined} identifier - The identifier parameter is the value used
218
+ * to identify the node to be deleted. It can be of any type that is returned by the callback
219
+ * function. It can also be null or undefined if no node needs to be deleted.
220
+ * @param {C} callback - The `callback` parameter is a function that takes a node of type `NODE` as
221
+ * input and returns a value of type `ReturnType<C>`. It is used to determine if a node matches the
222
+ * identifier for deletion. If no callback is provided, the `_defaultOneParamCallback` function is
223
+ * used
224
+ * @param [ignoreCount=false] - A boolean value indicating whether to ignore the count of the target
225
+ * node when performing deletion. If set to true, the count of the target node will not be considered
226
+ * and the node will be deleted regardless of its count. If set to false (default), the count of the
227
+ * target node will be decremented
228
+ * @returns an array of BinaryTreeDeleteResult<NODE> objects.
229
+ */
230
+ override delete<C extends BTNCallback<NODE>>(
231
+ identifier: ReturnType<C> | null | undefined,
232
+ callback: C = this._defaultOneParamCallback as C,
233
+ ignoreCount = false
234
+ ): BinaryTreeDeleteResult<NODE>[] {
235
+ const deleteResults: BinaryTreeDeleteResult<NODE>[] = [];
236
+ if (identifier === null) return deleteResults;
237
+
238
+ // Helper function to perform deletion
239
+ const deleteHelper = (node: NODE | undefined): void => {
240
+ // Initialize targetNode to the sentinel node
241
+ let targetNode: NODE = this._Sentinel;
242
+ let currentNode: NODE | undefined;
243
+
244
+ // Find the node to be deleted based on the identifier
245
+ while (node !== this._Sentinel) {
246
+ // Update targetNode if the current node matches the identifier
247
+ if (node && callback(node) === identifier) {
248
+ targetNode = node;
249
+ }
250
+
251
+ // Move to the right or left based on the comparison with the identifier
252
+ if (node && identifier && callback(node) <= identifier) {
253
+ node = node.right;
254
+ } else {
255
+ node = node?.left;
256
+ }
257
+ }
258
+
259
+ // If the target node is not found, decrement size and return
260
+ if (targetNode === this._Sentinel) {
261
+ return;
262
+ }
263
+
264
+ if (ignoreCount || targetNode.count <= 1) {
265
+ // Store the parent of the target node and its original color
266
+ let parentNode = targetNode;
267
+ let parentNodeOriginalColor: number = parentNode.color;
268
+
269
+ // Handle deletion based on the number of children of the target node
270
+ if (targetNode.left === this._Sentinel) {
271
+ // Target node has no left child - deletion case 1
272
+ currentNode = targetNode.right;
273
+ this._rbTransplant(targetNode, targetNode.right!);
274
+ } else if (targetNode.right === this._Sentinel) {
275
+ // Target node has no right child - deletion case 2
276
+ currentNode = targetNode.left;
277
+ this._rbTransplant(targetNode, targetNode.left!);
278
+ } else {
279
+ // Target node has both left and right children - deletion case 3
280
+ parentNode = this.getLeftMost(targetNode.right)!;
281
+ parentNodeOriginalColor = parentNode.color;
282
+ currentNode = parentNode.right;
283
+
284
+ if (parentNode.parent === targetNode) {
285
+ // Target node's right child becomes its parent's left child
286
+ currentNode!.parent = parentNode;
287
+ } else {
288
+ // Replace parentNode with its right child and update connections
289
+ this._rbTransplant(parentNode, parentNode.right!);
290
+ parentNode.right = targetNode.right;
291
+ parentNode.right!.parent = parentNode;
292
+ }
293
+
294
+ // Replace the target node with its in-order successor
295
+ this._rbTransplant(targetNode, parentNode);
296
+ parentNode.left = targetNode.left;
297
+ parentNode.left!.parent = parentNode;
298
+ parentNode.color = targetNode.color;
299
+ }
300
+
301
+ // Fix the Red-Black Tree properties after deletion
302
+ if (parentNodeOriginalColor === RBTNColor.BLACK) {
303
+ this._fixDelete(currentNode!);
304
+ }
305
+
306
+ // Decrement the size and store information about the deleted node
307
+ this._size--;
308
+ this._count -= targetNode.count;
309
+ deleteResults.push({ deleted: targetNode, needBalanced: undefined });
310
+ } else {
311
+ targetNode.count--;
312
+ this._count--;
313
+ }
314
+ };
315
+
316
+ // Call the helper function with the root of the tree
317
+ deleteHelper(this.root);
318
+
319
+ // Return the result array
320
+ return deleteResults;
321
+ }
322
+
323
+ /**
324
+ * Time Complexity: O(1)
325
+ * Space Complexity: O(1)
326
+ */
327
+
328
+ /**
329
+ * Time Complexity: O(1)
330
+ * Space Complexity: O(1)
331
+ *
332
+ * The "clear" function overrides the parent class's "clear" function and also resets the count to
333
+ * zero.
334
+ */
335
+ override clear() {
336
+ super.clear();
337
+ this._count = 0;
338
+ }
339
+
340
+ /**
341
+ * Time Complexity: O(n log n)
342
+ * Space Complexity: O(log n)
343
+ */
344
+
345
+ /**
346
+ * Time Complexity: O(n log n)
347
+ * Space Complexity: O(log n)
348
+ *
349
+ * The `perfectlyBalance` function takes a sorted array of nodes and builds a balanced binary search
350
+ * tree using either a recursive or iterative approach.
351
+ * @param iterationType - The `iterationType` parameter is an optional parameter that specifies the
352
+ * type of iteration to use when building the balanced binary search tree. It can have two possible
353
+ * values:
354
+ * @returns a boolean value.
355
+ */
356
+ override perfectlyBalance(iterationType = this.iterationType): boolean {
357
+ const sorted = this.dfs(node => node, 'in'),
358
+ n = sorted.length;
359
+ if (sorted.length < 1) return false;
360
+
361
+ this.clear();
362
+
363
+ if (iterationType === IterationType.RECURSIVE) {
364
+ const buildBalanceBST = (l: number, r: number) => {
365
+ if (l > r) return;
366
+ const m = l + Math.floor((r - l) / 2);
367
+ const midNode = sorted[m];
368
+ this.add(midNode.key, midNode.value, midNode.count);
369
+ buildBalanceBST(l, m - 1);
370
+ buildBalanceBST(m + 1, r);
371
+ };
372
+
373
+ buildBalanceBST(0, n - 1);
374
+ return true;
375
+ } else {
376
+ const stack: [[number, number]] = [[0, n - 1]];
377
+ while (stack.length > 0) {
378
+ const popped = stack.pop();
379
+ if (popped) {
380
+ const [l, r] = popped;
381
+ if (l <= r) {
382
+ const m = l + Math.floor((r - l) / 2);
383
+ const midNode = sorted[m];
384
+ this.add(midNode.key, midNode.value, midNode.count);
385
+ stack.push([m + 1, r]);
386
+ stack.push([l, m - 1]);
387
+ }
388
+ }
389
+ }
390
+ return true;
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Time complexity: O(n)
396
+ * Space complexity: O(n)
397
+ */
398
+
399
+ /**
400
+ * Time complexity: O(n)
401
+ * Space complexity: O(n)
402
+ *
403
+ * The function overrides the clone method to create a deep copy of a tree object.
404
+ * @returns The `clone()` method is returning a cloned instance of the `TREE` object.
405
+ */
406
+ override clone(): TREE {
407
+ const cloned = this.createTree();
408
+ this.bfs(node => cloned.add(node.key, node.value, node.count));
409
+ return cloned;
410
+ }
411
+
412
+ /**
413
+ * The function swaps the properties of two nodes in a binary search tree.
414
+ * @param srcNode - The source node that needs to be swapped with the destination node. It can be
415
+ * either a key or a node object.
416
+ * @param destNode - The `destNode` parameter is the node in the binary search tree where the
417
+ * properties will be swapped with the `srcNode`.
418
+ * @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
419
+ * If both `srcNode` and `destNode` are valid nodes, the method swaps their `key`, `value`, `count`,
420
+ * and `color` properties. If the swapping is successful, the method returns the modified `destNode`.
421
+ * If either `srcNode` or `destNode` is
422
+ */
423
+ protected override _swapProperties(
424
+ srcNode: BSTNKeyOrNode<K, NODE>,
425
+ destNode: BSTNKeyOrNode<K, NODE>
426
+ ): NODE | undefined {
427
+ srcNode = this.ensureNode(srcNode);
428
+ destNode = this.ensureNode(destNode);
429
+ if (srcNode && destNode) {
430
+ const { key, value, count, color } = destNode;
431
+ const tempNode = this.createNode(key, value, count);
432
+ if (tempNode) {
433
+ tempNode.color = color;
434
+
435
+ destNode.key = srcNode.key;
436
+ destNode.value = srcNode.value;
437
+ destNode.count = srcNode.count;
438
+ destNode.color = srcNode.color;
439
+
440
+ srcNode.key = tempNode.key;
441
+ srcNode.value = tempNode.value;
442
+ srcNode.count = tempNode.count;
443
+ srcNode.color = tempNode.color;
444
+ }
445
+
446
+ return destNode;
447
+ }
448
+ return undefined;
449
+ }
450
+
451
+ /**
452
+ * The function replaces an old node with a new node and updates the count property of the new node.
453
+ * @param {NODE} oldNode - The `oldNode` parameter is of type `NODE` and represents the node that
454
+ * needs to be replaced in the data structure.
455
+ * @param {NODE} newNode - The `newNode` parameter is an object of type `NODE`.
456
+ * @returns The method is returning the result of calling the `_replaceNode` method from the
457
+ * superclass, after updating the `count` property of the `newNode` object.
458
+ */
459
+ protected _replaceNode(oldNode: NODE, newNode: NODE): NODE {
460
+ newNode.count = oldNode.count + newNode.count;
461
+ return super._replaceNode(oldNode, newNode);
462
+ }
463
+ }
@@ -954,217 +954,6 @@ export abstract class AbstractGraph<
954
954
  return { costs, predecessor };
955
955
  }
956
956
 
957
- /**
958
- * Time Complexity: O(V + E) - Linear time (Tarjan's algorithm).
959
- * Space Complexity: O(V) - Linear space (Tarjan's algorithm).
960
- * Tarjan is an algorithm based on dfs,which is used to solve the connectivity problem of graphs.
961
- * Tarjan can find cycles in directed or undirected graph
962
- * Tarjan can find the articulation points and bridges(critical edgeMap) of undirected graphs in linear time,
963
- * Tarjan solve the bi-connected components of undirected graphs;
964
- * Tarjan can find the SSC(strongly connected components), articulation points, and bridges of directed graphs.
965
- * /
966
-
967
- /**
968
- * Time Complexity: O(V + E) - Linear time (Tarjan's algorithm).
969
- * Space Complexity: O(V) - Linear space (Tarjan's algorithm).
970
- *
971
- * Tarjan is an algorithm based on dfs,which is used to solve the connectivity problem of graphs.
972
- * Tarjan can find cycles in directed or undirected graph
973
- * Tarjan can find the articulation points and bridges(critical edgeMap) of undirected graphs in linear time,
974
- * Tarjan solve the bi-connected components of undirected graphs;
975
- * Tarjan can find the SSC(strongly connected components), articulation points, and bridges of directed graphs.
976
- * The `tarjan` function is used to perform various graph analysis tasks such as finding articulation points, bridges,
977
- * strongly connected components (SCCs), and cycles in a graph.
978
- * @param {boolean} [needCutVertexes] - A boolean value indicating whether or not to calculate and return the
979
- * articulation points in the graph. Articulation points are the vertexMap in a graph whose removal would increase the
980
- * number of connected components in the graph.
981
- * @param {boolean} [needBridges] - A boolean flag indicating whether the algorithm should find and return the bridges
982
- * (edgeMap whose removal would increase the number of connected components in the graph).
983
- * @param {boolean} [needSCCs] - A boolean value indicating whether the Strongly Connected Components (SCCs) of the
984
- * graph are needed. If set to true, the function will calculate and return the SCCs of the graph. If set to false, the
985
- * SCCs will not be calculated or returned.
986
- * @param {boolean} [needCycles] - A boolean flag indicating whether the algorithm should find cycles in the graph. If
987
- * set to true, the algorithm will return a map of cycles, where the keys are the low values of the SCCs and the values
988
- * are arrays of vertexMap that form cycles within the SCCs.
989
- * @returns The function `tarjan` returns an object with the following properties:
990
- */
991
- tarjan(
992
- needCutVertexes: boolean = false,
993
- needBridges: boolean = false,
994
- needSCCs: boolean = true,
995
- needCycles: boolean = false
996
- ) {
997
- // !! in undirected graph we will not let child visit parent when dfs
998
- // !! articulation point(in dfs search tree not in graph): (cur !== root && cur.has(child)) && (low(child) >= dfn(cur)) || (cur === root && cur.children() >= 2)
999
- // !! bridge: low(child) > dfn(cur)
1000
-
1001
- const defaultConfig = false;
1002
- if (needCutVertexes === undefined) needCutVertexes = defaultConfig;
1003
- if (needBridges === undefined) needBridges = defaultConfig;
1004
- if (needSCCs === undefined) needSCCs = defaultConfig;
1005
- if (needCycles === undefined) needCycles = defaultConfig;
1006
-
1007
- const dfnMap: Map<VO, number> = new Map();
1008
- const lowMap: Map<VO, number> = new Map();
1009
- const vertexMap = this._vertexMap;
1010
- vertexMap.forEach(v => {
1011
- dfnMap.set(v, -1);
1012
- lowMap.set(v, Infinity);
1013
- });
1014
-
1015
- const [root] = vertexMap.values();
1016
-
1017
- const cutVertexes: VO[] = [];
1018
- const bridges: EO[] = [];
1019
- let dfn = 0;
1020
- const dfs = (cur: VO, parent: VO | undefined) => {
1021
- dfn++;
1022
- dfnMap.set(cur, dfn);
1023
- lowMap.set(cur, dfn);
1024
-
1025
- const neighbors = this.getNeighbors(cur);
1026
- let childCount = 0; // child in dfs tree not child in graph
1027
- for (const neighbor of neighbors) {
1028
- if (neighbor !== parent) {
1029
- if (dfnMap.get(neighbor) === -1) {
1030
- childCount++;
1031
- dfs(neighbor, cur);
1032
- }
1033
- const childLow = lowMap.get(neighbor);
1034
- const curLow = lowMap.get(cur);
1035
- // TODO after no-non-undefined-assertion not ensure the logic
1036
- if (curLow !== undefined && childLow !== undefined) {
1037
- lowMap.set(cur, Math.min(curLow, childLow));
1038
- }
1039
- const curFromMap = dfnMap.get(cur);
1040
- if (childLow !== undefined && curFromMap !== undefined) {
1041
- if (needCutVertexes) {
1042
- if ((cur === root && childCount >= 2) || (cur !== root && childLow >= curFromMap)) {
1043
- // todo not ensure the logic if (cur === root && childCount >= 2 || ((cur !== root) && (childLow >= curFromMap))) {
1044
- cutVertexes.push(cur);
1045
- }
1046
- }
1047
-
1048
- if (needBridges) {
1049
- if (childLow > curFromMap) {
1050
- const edgeCurToNeighbor = this.getEdge(cur, neighbor);
1051
- if (edgeCurToNeighbor) {
1052
- bridges.push(edgeCurToNeighbor);
1053
- }
1054
- }
1055
- }
1056
- }
1057
- }
1058
- }
1059
- };
1060
-
1061
- dfs(root, undefined);
1062
-
1063
- let SCCs: Map<number, VO[]> = new Map();
1064
-
1065
- const getSCCs = () => {
1066
- const SCCs: Map<number, VO[]> = new Map();
1067
- lowMap.forEach((low, vertex) => {
1068
- if (!SCCs.has(low)) {
1069
- SCCs.set(low, [vertex]);
1070
- } else {
1071
- SCCs.get(low)?.push(vertex);
1072
- }
1073
- });
1074
- return SCCs;
1075
- };
1076
-
1077
- if (needSCCs) {
1078
- SCCs = getSCCs();
1079
- }
1080
-
1081
- const cycles: Map<number, VO[]> = new Map();
1082
-
1083
- if (needCycles) {
1084
- const visitedMap: Map<VO, boolean> = new Map();
1085
- const stack: VO[] = [];
1086
- const findCyclesDFS = (cur: VO, parent: VO | undefined) => {
1087
- visitedMap.set(cur, true);
1088
- stack.push(cur);
1089
-
1090
- const neighbors = this.getNeighbors(cur);
1091
-
1092
- for (const neighbor of neighbors) {
1093
- if (!visitedMap.get(neighbor)) {
1094
- findCyclesDFS(neighbor, cur);
1095
- } else if (stack.includes(neighbor) && neighbor !== parent) {
1096
- const cycleStartIndex = stack.indexOf(neighbor);
1097
- const cycle = stack.slice(cycleStartIndex);
1098
- const cycleLow = Math.min(...cycle.map(v => dfnMap.get(v) || Infinity));
1099
- cycles.set(cycleLow, cycle);
1100
- }
1101
- }
1102
-
1103
- stack.pop();
1104
- };
1105
-
1106
- vertexMap.forEach(v => {
1107
- if (!visitedMap.get(v)) {
1108
- findCyclesDFS(v, undefined);
1109
- }
1110
- });
1111
- }
1112
-
1113
- return { dfnMap, lowMap, bridges, cutVertexes, SCCs, cycles };
1114
- }
1115
-
1116
- /**
1117
- * Time Complexity: O(V + E) - Depends on the implementation (Tarjan's algorithm).
1118
- * Space Complexity: O(V) - Depends on the implementation (Tarjan's algorithm).
1119
- */
1120
-
1121
- /**
1122
- * Time Complexity: O(V + E) - Depends on the implementation (Tarjan's algorithm).
1123
- * Space Complexity: O(V) - Depends on the implementation (Tarjan's algorithm).
1124
- *
1125
- * The function returns a map that associates each vertex object with its corresponding depth-first
1126
- * number.
1127
- * @returns A Map object with keys of type VO and values of type number.
1128
- */
1129
- getDFNMap(): Map<VO, number> {
1130
- return this.tarjan(false, false, false, false).dfnMap;
1131
- }
1132
-
1133
- /**
1134
- * The function returns a Map object that contains the low values of each vertex in a Tarjan
1135
- * algorithm.
1136
- * @returns The method `getLowMap()` is returning a `Map` object with keys of type `VO` and values of
1137
- * type `number`.
1138
- */
1139
- getLowMap(): Map<VO, number> {
1140
- return this.tarjan(false, false, false, false).lowMap;
1141
- }
1142
-
1143
- /**
1144
- * The function "getCutVertexes" returns an array of cut vertexes using the Tarjan algorithm.
1145
- * @returns an array of VO objects, specifically the cut vertexes.
1146
- */
1147
- getCutVertexes(): VO[] {
1148
- return this.tarjan(true, false, false, false).cutVertexes;
1149
- }
1150
-
1151
- /**
1152
- * The function "getSCCs" returns a map of strongly connected components (SCCs) using the Tarjan
1153
- * algorithm.
1154
- * @returns a map where the keys are numbers and the values are arrays of VO objects.
1155
- */
1156
- getSCCs(): Map<number, VO[]> {
1157
- return this.tarjan(false, false, true, false).SCCs;
1158
- }
1159
-
1160
- /**
1161
- * The function "getBridges" returns an array of bridges using the Tarjan algorithm.
1162
- * @returns the bridges found using the Tarjan algorithm.
1163
- */
1164
- getBridges() {
1165
- return this.tarjan(false, true, false, false).bridges;
1166
- }
1167
-
1168
957
  /**
1169
958
  * O(V+E+C)
1170
959
  * O(V+C)