data-structure-typed 2.2.6 → 2.2.7
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.
- package/CHANGELOG.md +1 -1
- package/CONTRIBUTING.md +47 -1
- package/README.md +6 -6
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs-legacy/index.cjs +3 -0
- package/dist/cjs-legacy/index.cjs.map +1 -1
- package/dist/esm/index.mjs +3 -0
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm-legacy/index.mjs +3 -0
- package/dist/esm-legacy/index.mjs.map +1 -1
- package/dist/umd/data-structure-typed.js +3 -0
- package/dist/umd/data-structure-typed.js.map +1 -1
- package/dist/umd/data-structure-typed.min.js +2 -2
- package/dist/umd/data-structure-typed.min.js.map +1 -1
- package/package.json +2 -2
- package/tsup.config.js +2 -2
- package/tsup.leetcode.config.js +1 -1
- package/tsup.node.config.js +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-entry-base.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/utils/utils.ts","../../src/utils/number.ts","../../src/data-structures/hash/hash-map.ts","../../src/data-structures/base/linear-base.ts","../../src/data-structures/linked-list/singly-linked-list.ts","../../src/data-structures/linked-list/doubly-linked-list.ts","../../src/data-structures/linked-list/skip-linked-list.ts","../../src/data-structures/stack/stack.ts","../../src/data-structures/queue/queue.ts","../../src/data-structures/queue/deque.ts","../../src/data-structures/heap/heap.ts","../../src/data-structures/heap/max-heap.ts","../../src/data-structures/heap/min-heap.ts","../../src/data-structures/graph/abstract-graph.ts","../../src/data-structures/graph/directed-graph.ts","../../src/data-structures/graph/undirected-graph.ts","../../src/data-structures/graph/map-graph.ts","../../src/common/index.ts","../../src/data-structures/binary-tree/binary-tree.ts","../../src/data-structures/binary-tree/bst.ts","../../src/data-structures/binary-tree/binary-indexed-tree.ts","../../src/data-structures/binary-tree/segment-tree.ts","../../src/data-structures/binary-tree/avl-tree.ts","../../src/data-structures/binary-tree/red-black-tree.ts","../../src/data-structures/binary-tree/avl-tree-multi-map.ts","../../src/data-structures/binary-tree/tree-multi-map.ts","../../src/data-structures/binary-tree/tree-counter.ts","../../src/data-structures/binary-tree/avl-tree-counter.ts","../../src/data-structures/priority-queue/priority-queue.ts","../../src/data-structures/priority-queue/min-priority-queue.ts","../../src/data-structures/priority-queue/max-priority-queue.ts","../../src/data-structures/matrix/matrix.ts","../../src/data-structures/matrix/navigator.ts","../../src/data-structures/trie/trie.ts","../../src/data-structures/tree/tree.ts"],"sourcesContent":["export * from './data-structures';\nexport * from './utils';\nexport * from './interfaces';\nexport * from './types';\nexport * from './common';\n","import type { EntryCallback, ReduceEntryCallback } from '../../types';\n\n/**\n * Iterable view over key-value entries.\n * @template K - Key type.\n * @template V - Value type.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class IterableEntryBase<K = any, V = any> {\n /**\n * Total number of entries.\n * @returns Entry count.\n * @remarks Time O(1), Space O(1)\n */\n abstract get size(): number;\n\n /**\n * Default iterator yielding `[key, value]` entries.\n * @returns Iterator of `[K, V]`.\n * @remarks Time O(n) to iterate, Space O(1)\n */\n *[Symbol.iterator](...args: any[]): IterableIterator<[K, V]> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Iterate over `[key, value]` pairs (may yield `undefined` values).\n * @returns Iterator of `[K, V | undefined]`.\n * @remarks Time O(n), Space O(1)\n */\n *entries(): IterableIterator<[K, V | undefined]> {\n for (const item of this) {\n yield item;\n }\n }\n\n /**\n * Iterate over keys only.\n * @returns Iterator of keys.\n * @remarks Time O(n), Space O(1)\n */\n *keys(): IterableIterator<K> {\n for (const item of this) {\n yield item[0];\n }\n }\n\n /**\n * Iterate over values only.\n * @returns Iterator of values.\n * @remarks Time O(n), Space O(1)\n */\n *values(): IterableIterator<V> {\n for (const item of this) {\n yield item[1];\n }\n }\n\n /**\n * Test whether all entries satisfy the predicate.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns `true` if all pass; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n every(predicate: EntryCallback<K, V, boolean>, thisArg?: any): boolean {\n let index = 0;\n for (const item of this) {\n if (!predicate.call(thisArg, item[1], item[0], index++, this)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Test whether any entry satisfies the predicate.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns `true` if any passes; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n some(predicate: EntryCallback<K, V, boolean>, thisArg?: any): boolean {\n let index = 0;\n for (const item of this) {\n if (predicate.call(thisArg, item[1], item[0], index++, this)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Visit each entry, left-to-right.\n * @param callbackfn - `(key, value, index, self) => void`.\n * @param thisArg - Optional `this` for callback.\n * @remarks Time O(n), Space O(1)\n */\n forEach(callbackfn: EntryCallback<K, V, void>, thisArg?: any): void {\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n callbackfn.call(thisArg, value, key, index++, this);\n }\n }\n\n /**\n * Find the first entry that matches a predicate.\n * @param callbackfn - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns Matching `[key, value]` or `undefined`.\n * @remarks Time O(n), Space O(1)\n */\n find(callbackfn: EntryCallback<K, V, boolean>, thisArg?: any): [K, V] | undefined {\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n if (callbackfn.call(thisArg, value, key, index++, this)) return item;\n }\n return;\n }\n\n /**\n * Whether the given key exists.\n * @param key - Key to test.\n * @returns `true` if found; otherwise `false`.\n * @remarks Time O(n) generic, Space O(1)\n */\n has(key: K): boolean {\n for (const item of this) {\n const [itemKey] = item;\n if (itemKey === key) return true;\n }\n return false;\n }\n\n /**\n * Whether there exists an entry with the given value.\n * @param value - Value to test.\n * @returns `true` if found; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n hasValue(value: V): boolean {\n for (const [, elementValue] of this) {\n if (elementValue === value) return true;\n }\n return false;\n }\n\n /**\n * Get the value under a key.\n * @param key - Key to look up.\n * @returns Value or `undefined`.\n * @remarks Time O(n) generic, Space O(1)\n */\n get(key: K): V | undefined {\n for (const item of this) {\n const [itemKey, value] = item;\n if (itemKey === key) return value;\n }\n return;\n }\n\n /**\n * Reduce entries into a single accumulator.\n * @param callbackfn - `(acc, value, key, index, self) => acc`.\n * @param initialValue - Initial accumulator.\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n reduce<U>(callbackfn: ReduceEntryCallback<K, V, U>, initialValue: U): U {\n let accumulator = initialValue;\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n accumulator = callbackfn(accumulator, value, key, index++, this);\n }\n return accumulator;\n }\n\n /**\n * Converts data structure to `[key, value]` pairs.\n * @returns Array of entries.\n * @remarks Time O(n), Space O(n)\n */\n toArray() {\n return [...this];\n }\n\n /**\n * Visualize the iterable as an array of `[key, value]` pairs (or a custom string).\n * @returns Array of entries (default) or a string.\n * @remarks Time O(n), Space O(n)\n */\n toVisual(): [K, V][] | string {\n return [...this];\n }\n\n /**\n * Print a human-friendly representation to the console.\n * @remarks Time O(n), Space O(n)\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Whether there are no entries.\n * @returns `true` if empty; `false` otherwise.\n * @remarks Time O(1) typical, Space O(1)\n */\n abstract isEmpty(): boolean;\n\n /**\n * Remove all entries.\n * @remarks Time O(n) typical, Space O(1)\n */\n abstract clear(): void;\n\n /**\n * Deep clone preserving the concrete subtype.\n * @returns A new instance of the same concrete class (`this` type).\n * @remarks Time O(n) typical, Space O(n)\n */\n abstract clone(): this;\n\n /**\n * Map entries using an implementation-specific strategy.\n * @remarks Time O(n), Space O(n)\n */\n abstract map(...args: any[]): any;\n\n /**\n * Filter entries and return the same-species structure.\n * @returns A new instance of the same concrete class (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n abstract filter(...args: any[]): this;\n\n /**\n * Underlying iterator for the default iteration protocol.\n * @returns Iterator of `[K, V]`.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getIterator(...args: any[]): IterableIterator<[K, V]>;\n}\n","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Comparable, ComparablePrimitive, Trampoline, TrampolineThunk } from '../types';\n\n/**\n * The function generates a random UUID (Universally Unique Identifier) in TypeScript.\n * @returns A randomly generated UUID (Universally Unique Identifier) in the format\n * 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' where each 'x' is replaced with a random hexadecimal\n * character.\n */\nexport const uuidV4 = function () {\n return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {\n const r = (Math.random() * 16) | 0,\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\n/**\n * The `arrayRemove` function removes elements from an array based on a specified predicate function\n * and returns the removed elements.\n * @param {T[]} array - An array of elements that you want to filter based on the provided predicate\n * function.\n * @param predicate - The `predicate` parameter is a function that takes three arguments:\n * @returns The `arrayRemove` function returns an array containing the elements that satisfy the given\n * `predicate` function.\n */\nexport const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {\n let i = -1,\n len = array ? array.length : 0;\n const result = [];\n\n while (++i < len) {\n const value = array[i];\n if (predicate(value, i, array)) {\n result.push(value);\n Array.prototype.splice.call(array, i--, 1);\n len--;\n }\n }\n\n return result;\n};\n\n/**\n * The function `getMSB` returns the most significant bit of a given number.\n * @param {number} value - The `value` parameter is a number for which we want to find the position of\n * the Most Significant Bit (MSB). The function `getMSB` takes this number as input and calculates the\n * position of the MSB in its binary representation.\n * @returns The function `getMSB` returns the most significant bit (MSB) of the input `value`. If the\n * input value is less than or equal to 0, it returns 0. Otherwise, it calculates the position of the\n * MSB using the `Math.clz32` function and bitwise left shifts 1 to that position.\n */\nexport const getMSB = (value: number): number => {\n if (value <= 0) {\n return 0;\n }\n return 1 << (31 - Math.clz32(value));\n};\n\n/**\n * The `rangeCheck` function in TypeScript is used to validate if an index is within a specified range\n * and throws a `RangeError` with a custom message if it is out of bounds.\n * @param {number} index - The `index` parameter represents the value that you want to check if it\n * falls within a specified range.\n * @param {number} min - The `min` parameter represents the minimum value that the `index` should be\n * compared against in the `rangeCheck` function.\n * @param {number} max - The `max` parameter in the `rangeCheck` function represents the maximum value\n * that the `index` parameter is allowed to have. If the `index` is greater than this `max` value, a\n * `RangeError` will be thrown.\n * @param [message=Index out of bounds.] - The `message` parameter is a string that represents the\n * error message to be thrown if the index is out of bounds. By default, if no message is provided when\n * calling the `rangeCheck` function, the message \"Index out of bounds.\" will be used.\n */\nexport const rangeCheck = (index: number, min: number, max: number, message = 'Index out of bounds.'): void => {\n if (index < min || index > max) throw new RangeError(message);\n};\n\n/**\n * The function `throwRangeError` throws a RangeError with a custom message if called.\n * @param [message=The value is off-limits.] - The `message` parameter is a string that represents the\n * error message to be displayed when a `RangeError` is thrown. If no message is provided, the default\n * message is 'The value is off-limits.'.\n */\nexport const throwRangeError = (message = 'The value is off-limits.'): void => {\n throw new RangeError(message);\n};\n\n/**\n * The function `isWeakKey` checks if the input is an object or a function in TypeScript.\n * @param {unknown} input - The `input` parameter in the `isWeakKey` function is of type `unknown`,\n * which means it can be any type. The function checks if the `input` is an object (excluding `null`)\n * or a function, and returns a boolean indicating whether the `input` is a weak\n * @returns The function `isWeakKey` returns a boolean value indicating whether the input is an object\n * or a function.\n */\nexport const isWeakKey = (input: unknown): input is object => {\n const inputType = typeof input;\n return (inputType === 'object' && input !== null) || inputType === 'function';\n};\n\n/**\n * The function `calcMinUnitsRequired` calculates the minimum number of units required to accommodate a\n * given total quantity based on a specified unit size.\n * @param {number} totalQuantity - The `totalQuantity` parameter represents the total quantity of items\n * that need to be processed or handled.\n * @param {number} unitSize - The `unitSize` parameter represents the size of each unit or package. It\n * is used in the `calcMinUnitsRequired` function to calculate the minimum number of units required to\n * accommodate a total quantity of items.\n */\nexport const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) =>\n Math.floor((totalQuantity + unitSize - 1) / unitSize);\n\n/**\n * The `roundFixed` function in TypeScript rounds a number to a specified number of decimal places.\n * @param {number} num - The `num` parameter is a number that you want to round to a certain number of\n * decimal places.\n * @param {number} [digit=10] - The `digit` parameter in the `roundFixed` function specifies the number\n * of decimal places to round the number to. By default, it is set to 10 if not provided explicitly.\n * @returns The function `roundFixed` returns a number that is rounded to the specified number of\n * decimal places (default is 10 decimal places).\n */\nexport const roundFixed = (num: number, digit: number = 10) => {\n const multiplier = Math.pow(10, digit);\n return Math.round(num * multiplier) / multiplier;\n};\n\n/**\n * The function `isPrimitiveComparable` checks if a value is a primitive type that can be compared.\n * @param {unknown} value - The `value` parameter in the `isPrimitiveComparable` function is of type\n * `unknown`, which means it can be any type. The function checks if the `value` is a primitive type\n * that can be compared, such as number, bigint, string, or boolean.\n * @returns The function `isPrimitiveComparable` returns a boolean value indicating whether the input\n * `value` is a primitive value that can be compared using standard comparison operators (<, >, <=,\n * >=).\n */\nfunction isPrimitiveComparable(value: unknown): value is ComparablePrimitive {\n const valueType = typeof value;\n if (valueType === 'number') return true;\n // if (valueType === 'number') return !Number.isNaN(value);\n return valueType === 'bigint' || valueType === 'string' || valueType === 'boolean';\n}\n\n/**\n * The function `tryObjectToPrimitive` attempts to convert an object to a comparable primitive value by\n * first checking the `valueOf` method and then the `toString` method.\n * @param {object} obj - The `obj` parameter in the `tryObjectToPrimitive` function is an object that\n * you want to convert to a primitive value. The function attempts to convert the object to a primitive\n * value by first checking if the object has a `valueOf` method. If the `valueOf` method exists, it\n * @returns The function `tryObjectToPrimitive` returns a value of type `ComparablePrimitive` if a\n * primitive comparable value is found within the object, or a string value if the object has a custom\n * `toString` method that does not return `'[object Object]'`. If neither condition is met, the\n * function returns `null`.\n */\nfunction tryObjectToPrimitive(obj: object): ComparablePrimitive | null {\n if (typeof obj.valueOf === 'function') {\n const valueOfResult = obj.valueOf();\n if (valueOfResult !== obj) {\n if (isPrimitiveComparable(valueOfResult)) return valueOfResult;\n if (typeof valueOfResult === 'object' && valueOfResult !== null) return tryObjectToPrimitive(valueOfResult);\n }\n }\n if (typeof obj.toString === 'function') {\n const stringResult = obj.toString();\n if (stringResult !== '[object Object]') return stringResult;\n }\n return null;\n}\n\n/**\n * The function `isComparable` in TypeScript checks if a value is comparable, handling primitive values\n * and objects with optional force comparison.\n * @param {unknown} value - The `value` parameter in the `isComparable` function represents the value\n * that you want to check if it is comparable. It can be of any type (`unknown`), and the function will\n * determine if it is comparable based on certain conditions.\n * @param [isForceObjectComparable=false] - The `isForceObjectComparable` parameter in the\n * `isComparable` function is a boolean flag that determines whether to treat non-primitive values as\n * comparable objects. When set to `true`, it forces the function to consider non-primitive values as\n * comparable objects, regardless of their type.\n * @returns The function `isComparable` returns a boolean value indicating whether the `value` is\n * considered comparable or not.\n */\nexport function isComparable(value: unknown, isForceObjectComparable = false): value is Comparable {\n if (value === null || value === undefined) return false;\n if (isPrimitiveComparable(value)) return true;\n\n if (typeof value !== 'object') return false;\n if (value instanceof Date) return true;\n // if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (isForceObjectComparable) return true;\n const comparableValue = tryObjectToPrimitive(value);\n if (comparableValue === null || comparableValue === undefined) return false;\n return isPrimitiveComparable(comparableValue);\n}\n\n/**\n * Creates a trampoline thunk object.\n *\n * A \"thunk\" is a deferred computation — instead of performing a recursive call immediately,\n * it wraps the next step of the computation in a function. This allows recursive processes\n * to be executed iteratively, preventing stack overflows.\n *\n * @template T - The type of the final computation result.\n * @param computation - A function that, when executed, returns the next trampoline step.\n * @returns A TrampolineThunk object containing the deferred computation.\n */\nexport const makeTrampolineThunk = <T>(computation: () => Trampoline<T>): TrampolineThunk<T> => ({\n isThunk: true, // Marker indicating this is a thunk\n fn: computation // The deferred computation function\n});\n\n/**\n * Type guard to check whether a given value is a TrampolineThunk.\n *\n * This function is used to distinguish between a final computation result (value)\n * and a deferred computation (thunk).\n *\n * @template T - The type of the value being checked.\n * @param value - The value to test.\n * @returns True if the value is a valid TrampolineThunk, false otherwise.\n */\nexport const isTrampolineThunk = <T>(value: Trampoline<T>): value is TrampolineThunk<T> =>\n typeof value === 'object' && // Must be an object\n value !== null && // Must not be null\n 'isThunk' in value && // Must have the 'isThunk' property\n value.isThunk; // The flag must be true\n\n/**\n * Executes a trampoline computation until a final (non-thunk) result is obtained.\n *\n * The trampoline function repeatedly invokes the deferred computations (thunks)\n * in an iterative loop. This avoids deep recursive calls and prevents stack overflow,\n * which is particularly useful for implementing recursion in a stack-safe manner.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline value or thunk to start execution from.\n * @returns The final result of the computation (a non-thunk value).\n */\nexport function trampoline<T>(initial: Trampoline<T>): T {\n let current = initial; // Start with the initial trampoline value\n while (isTrampolineThunk(current)) {\n // Keep unwrapping while we have thunks\n current = current.fn(); // Execute the deferred function to get the next step\n }\n return current; // Once no thunks remain, return the final result\n}\n\n/**\n * Wraps a recursive function inside a trampoline executor.\n *\n * This function transforms a potentially recursive function (that returns a Trampoline<Result>)\n * into a *stack-safe* function that executes iteratively using the `trampoline` runner.\n *\n * In other words, it allows you to write functions that look recursive,\n * but actually run in constant stack space.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all trampoline steps are resolved.\n *\n * @param fn - A function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns A new function with the same arguments, but which automatically\n * runs the trampoline process and returns the *final result* instead\n * of a Trampoline.\n *\n * @example\n * // Example: Computing factorial in a stack-safe way\n * const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * console.log(factorial(100000)); // Works without stack overflow\n */\nexport function makeTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> // A function that returns a trampoline step\n): (...args: Args) => Result {\n // Return a wrapped function that automatically runs the trampoline execution loop\n return (...args: Args) => trampoline(fn(...args));\n}\n\n/**\n * Executes an asynchronous trampoline computation until a final (non-thunk) result is obtained.\n *\n * This function repeatedly invokes asynchronous deferred computations (thunks)\n * in an iterative loop. Each thunk may return either a Trampoline<T> or a Promise<Trampoline<T>>.\n *\n * It ensures that asynchronous recursive functions can run without growing the call stack,\n * making it suitable for stack-safe async recursion.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline or Promise of Trampoline to start execution from.\n * @returns A Promise that resolves to the final result (a non-thunk value).\n */\nexport async function asyncTrampoline<T>(initial: Trampoline<T> | Promise<Trampoline<T>>): Promise<T> {\n let current = await initial; // Wait for the initial step to resolve if it's a Promise\n\n // Keep executing thunks until we reach a non-thunk (final) value\n while (isTrampolineThunk(current)) {\n current = await current.fn(); // Execute the thunk function (may be async)\n }\n\n // Once the final value is reached, return it\n return current;\n}\n\n/**\n * Wraps an asynchronous recursive function inside an async trampoline executor.\n *\n * This helper transforms a recursive async function that returns a Trampoline<Result>\n * (or Promise<Trampoline<Result>>) into a *stack-safe* async function that executes\n * iteratively via the `asyncTrampoline` runner.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all async trampoline steps are resolved.\n *\n * @param fn - An async or sync function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns An async function with the same arguments, but which automatically\n * runs the trampoline process and resolves to the *final result*.\n *\n * @example\n * // Example: Async factorial using trampoline\n * const asyncFactorial = makeAsyncTrampoline(async function fact(\n * n: number,\n * acc: number = 1\n * ): Promise<Trampoline<number>> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * asyncFactorial(100000).then(console.log); // Works without stack overflow\n */\nexport function makeAsyncTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>\n): (...args: Args) => Promise<Result> {\n // Return a wrapped async function that runs through the async trampoline loop\n return async (...args: Args): Promise<Result> => {\n return asyncTrampoline(fn(...args));\n };\n}\n","/**\n * The function `toBinaryString` converts a number to a binary string representation with a specified\n * number of digits.\n * @param {number} num - The `num` parameter in the `toBinaryString` function represents the number\n * that you want to convert to a binary string.\n * @param [digit=32] - The `digit` parameter in the `toBinaryString` function represents the number of\n * digits the binary string should have. By default, it is set to 32, meaning that the binary string\n * will be padded with zeros at the beginning to ensure it is 32 bits long. You can provide a\n * @returns The function `toBinaryString` takes a number as input and converts it to a binary string\n * representation with a specified number of digits (default is 32). The binary string is padded with\n * zeros at the beginning to ensure it has the specified number of digits. The function returns the\n * binary string representation of the input number.\n */\nexport function toBinaryString(num: number, digit = 32) {\n // Convert number to binary string\n let binaryString = (num >>> 0).toString(2); // Use the unsigned right shift operator to ensure you get a binary representation of a 32-bit unsigned integer\n\n // Use pad Start to ensure the string length is 32 bits\n binaryString = binaryString.padStart(digit, '0');\n\n return binaryString;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n EntryCallback,\n HashMapLinkedNode,\n HashMapOptions,\n HashMapStoreItem,\n LinkedHashMapOptions\n} from '../../types';\nimport { IterableEntryBase } from '../base';\nimport { isWeakKey, rangeCheck } from '../../utils';\n\n/**\n * Hash-based map. Supports object keys and custom hashing; offers O(1) average set/get/has.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n * 1. Key-Value Pair Storage: HashMap stores key-value pairs. Each key map to a value.\n * 2. Fast Lookup: It's used when you need to quickly find, insert, or delete entries based on a key.\n * 3. Unique Keys: Keys are unique.\n * If you try to insert another entry with the same key, the new one will replace the old entry.\n * 4. Unordered Collection: HashMap does not guarantee the order of entries, and the order may change over time.\n * @example\n * // should maintain insertion order\n * const linkedHashMap = new LinkedHashMap<number, string>();\n * linkedHashMap.set(1, 'A');\n * linkedHashMap.set(2, 'B');\n * linkedHashMap.set(3, 'C');\n *\n * const result = Array.from(linkedHashMap);\n * console.log(result); // [\n * // [1, 'A'],\n * // [2, 'B'],\n * // [3, 'C']\n * // ];\n * @example\n * // basic HashMap creation and set operation\n * // Create a simple HashMap with key-value pairs\n * const map = new HashMap<number, string>([\n * [1, 'one'],\n * [2, 'two'],\n * [3, 'three']\n * ]);\n *\n * // Verify size\n * console.log(map.size); // 3;\n *\n * // Set a new key-value pair\n * map.set(4, 'four');\n * console.log(map.size); // 4;\n *\n * // Verify entries\n * console.log([...map.entries()]); // length: 4;\n * @example\n * // HashMap get and has operations\n * const map = new HashMap<string, number>([\n * ['apple', 1],\n * ['banana', 2],\n * ['cherry', 3]\n * ]);\n *\n * // Check if key exists\n * console.log(map.has('apple')); // true;\n * console.log(map.has('date')); // false;\n *\n * // Get value by key\n * console.log(map.get('banana')); // 2;\n * console.log(map.get('grape')); // undefined;\n *\n * // Get all keys and values\n * const keys = [...map.keys()];\n * const values = [...map.values()];\n * console.log(keys); // contains 'apple';\n * console.log(values); // contains 3;\n * @example\n * // HashMap iteration and filter operations\n * const map = new HashMap<number, string>([\n * [1, 'Alice'],\n * [2, 'Bob'],\n * [3, 'Charlie'],\n * [4, 'Diana'],\n * [5, 'Eve']\n * ]);\n *\n * // Iterate through entries\n * const entries: [number, string][] = [];\n * for (const [key, value] of map) {\n * entries.push([key, value]);\n * }\n * console.log(entries); // length: 5;\n *\n * // Filter operation (for iteration with collection methods)\n * const filtered = [...map].filter(([key]) => key > 2);\n * console.log(filtered.length); // 3;\n *\n * // Map operation\n * const values = [...map.values()].map(v => v.length);\n * console.log(values); // contains 3; // 'Bob', 'Eve'\n * console.log(values); // contains 7;\n * @example\n * // HashMap for user session caching O(1) performance\n * interface UserSession {\n * userId: number;\n * username: string;\n * loginTime: number;\n * lastActivity: number;\n * }\n *\n * // HashMap provides O(1) average-case performance for set/get/delete\n * // Perfect for session management with fast lookups\n * const sessionCache = new HashMap<string, UserSession>();\n *\n * // Simulate user sessions\n * const sessions: [string, UserSession][] = [\n * ['session_001', { userId: 1, username: 'alice', loginTime: 1000, lastActivity: 1050 }],\n * ['session_002', { userId: 2, username: 'bob', loginTime: 1100, lastActivity: 1150 }],\n * ['session_003', { userId: 3, username: 'charlie', loginTime: 1200, lastActivity: 1250 }]\n * ];\n *\n * // Store sessions with O(1) insertion\n * for (const [token, session] of sessions) {\n * sessionCache.set(token, session);\n * }\n *\n * console.log(sessionCache.size); // 3;\n *\n * // Retrieve session with O(1) lookup\n * const userSession = sessionCache.get('session_001');\n * console.log(userSession?.username); // 'alice';\n * console.log(userSession?.userId); // 1;\n *\n * // Update session with O(1) operation\n * if (userSession) {\n * userSession.lastActivity = 2000;\n * sessionCache.set('session_001', userSession);\n * }\n *\n * // Check updated value\n * const updated = sessionCache.get('session_001');\n * console.log(updated?.lastActivity); // 2000;\n *\n * // Cleanup: delete expired sessions\n * sessionCache.delete('session_002');\n * console.log(sessionCache.has('session_002')); // false;\n *\n * // Verify remaining sessions\n * console.log(sessionCache.size); // 2;\n *\n * // Get all active sessions\n * const activeCount = [...sessionCache.values()].length;\n * console.log(activeCount); // 2;\n */\nexport class HashMap<K = any, V = any, R = [K, V]> extends IterableEntryBase<K, V> {\n /**\n * Create a HashMap and optionally bulk-insert entries.\n * @remarks Time O(N), Space O(N)\n * @param [entryOrRawElements] - Iterable of entries or raw elements to insert.\n * @param [options] - Options: hash function and optional record-to-entry converter.\n * @returns New HashMap instance.\n */\n constructor(entryOrRawElements: Iterable<R | [K, V]> = [], options?: HashMapOptions<K, V, R>) {\n super();\n if (options) {\n const { hashFn, toEntryFn } = options;\n if (hashFn) this._hashFn = hashFn;\n if (toEntryFn) this._toEntryFn = toEntryFn;\n }\n if (entryOrRawElements) this.setMany(entryOrRawElements);\n }\n\n protected _store: { [key: string]: HashMapStoreItem<K, V> } = {};\n\n /**\n * Get the internal store for non-object keys.\n * @remarks Time O(1), Space O(1)\n * @returns Internal record of string→{key,value}.\n */\n get store(): { [p: string]: HashMapStoreItem<K, V> } {\n return this._store;\n }\n\n protected _objMap: Map<object, V> = new Map();\n\n /**\n * Get the internal Map used for object/function keys.\n * @remarks Time O(1), Space O(1)\n * @returns Map of object→value.\n */\n get objMap(): Map<object, V> {\n return this._objMap;\n }\n\n protected _toEntryFn?: (rawElement: R) => [K, V];\n\n /**\n * Get the raw→entry converter function if present.\n * @remarks Time O(1), Space O(1)\n * @returns Converter function or undefined.\n */\n get toEntryFn() {\n return this._toEntryFn;\n }\n\n protected _size = 0;\n\n /**\n * Get the number of distinct keys stored.\n * @remarks Time O(1), Space O(1)\n * @returns Current size.\n */\n get size(): number {\n return this._size;\n }\n\n protected _hashFn: (key: K) => string = (key: K) => String(key);\n\n /**\n * Get the current hash function for non-object keys.\n * @remarks Time O(1), Space O(1)\n * @returns Hash function.\n */\n get hashFn() {\n return this._hashFn;\n }\n\n /**\n * Check whether the map is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Remove all entries and reset counters.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n clear(): void {\n this._store = {};\n this._objMap.clear();\n this._size = 0;\n }\n\n /**\n * Type guard: check if a raw value is a [key, value] entry.\n * @remarks Time O(1), Space O(1)\n * @returns True if the value is a 2-tuple.\n */\n isEntry(rawElement: any): rawElement is [K, V] {\n return Array.isArray(rawElement) && rawElement.length === 2;\n }\n\n /**\n * Insert or replace a single entry.\n * @remarks Time O(1), Space O(1)\n * @param key - Key.\n * @param value - Value.\n * @returns True when the operation succeeds.\n */\n set(key: K, value: V): boolean {\n if (this._isObjKey(key)) {\n if (!this.objMap.has(key)) this._size++;\n this.objMap.set(key, value);\n } else {\n const strKey = this._getNoObjKey(key);\n if (this.store[strKey] === undefined) this._size++;\n this._store[strKey] = { key, value };\n }\n return true;\n }\n\n /**\n * Insert many entries from an iterable.\n * @remarks Time O(N), Space O(N)\n * @param entryOrRawElements - Iterable of entries or raw elements to insert.\n * @returns Array of per-entry results.\n */\n setMany(entryOrRawElements: Iterable<R | [K, V]>): boolean[] {\n const results: boolean[] = [];\n for (const rawEle of entryOrRawElements) {\n let key: K | undefined, value: V | undefined;\n if (this.isEntry(rawEle)) [key, value] = rawEle;\n else if (this._toEntryFn) [key, value] = this._toEntryFn(rawEle);\n if (key !== undefined && value !== undefined) results.push(this.set(key, value));\n }\n return results;\n }\n\n /**\n * Get the value for a key.\n * @remarks Time O(1), Space O(1)\n * @param key - Key to look up.\n * @returns Value or undefined.\n */\n override get(key: K): V | undefined {\n if (this._isObjKey(key)) return this.objMap.get(key);\n const strKey = this._getNoObjKey(key);\n return this._store[strKey]?.value;\n }\n\n /**\n * Check if a key exists.\n * @remarks Time O(1), Space O(1)\n * @param key - Key to test.\n * @returns True if present.\n */\n override has(key: K): boolean {\n if (this._isObjKey(key)) return this.objMap.has(key);\n const strKey = this._getNoObjKey(key);\n return strKey in this.store;\n }\n\n /**\n * Delete an entry by key.\n * @remarks Time O(1), Space O(1)\n * @param key - Key to delete.\n * @returns True if the key was found and removed.\n */\n delete(key: K): boolean {\n if (this._isObjKey(key)) {\n if (this.objMap.has(key)) this._size--;\n return this.objMap.delete(key);\n }\n const strKey = this._getNoObjKey(key);\n if (strKey in this.store) {\n delete this.store[strKey];\n this._size--;\n return true;\n }\n return false;\n }\n\n /**\n * Replace the hash function and rehash the non-object store.\n * @remarks Time O(N), Space O(N)\n * @param fn - New hash function for non-object keys.\n * @returns This map instance.\n */\n setHashFn(fn: (key: K) => string): this {\n if (this._hashFn === fn) return this;\n this._hashFn = fn;\n this._rehashNoObj();\n return this;\n }\n\n /**\n * Deep clone this map, preserving hashing behavior.\n * @remarks Time O(N), Space O(N)\n * @returns A new map with the same content.\n */\n clone(): this {\n const opts = { hashFn: this._hashFn, toEntryFn: this._toEntryFn };\n return this._createLike<[K, V], [K, V], [K, V]>(this, opts);\n }\n\n /**\n * Map values to a new map with the same keys.\n * @remarks Time O(N), Space O(N)\n * @template VM\n * @param callbackfn - Mapping function (key, value, index, map) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new map with transformed values.\n */\n map<VM>(callbackfn: EntryCallback<K, V, VM>, thisArg?: any): any {\n const out = this._createLike<K, VM, [K, VM]>();\n let index = 0;\n for (const [key, value] of this) out.set(key, callbackfn.call(thisArg, value, key, index++, this));\n return out;\n }\n\n /**\n * Filter entries into a new map.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (key, value, index, map) → boolean.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new map containing entries that satisfied the predicate.\n */\n\n filter(predicate: EntryCallback<K, V, boolean>, thisArg?: any): any {\n const out = this._createLike<K, V, [K, V]>();\n let index = 0;\n for (const [key, value] of this) if (predicate.call(thisArg, value, key, index++, this)) out.set(key, value);\n return out;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param [entries] - Iterable used to seed the new map.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind map instance.\n */\n protected _createLike<TK = K, TV = V, TR = [TK, TV]>(entries: Iterable<[TK, TV] | TR> = [], options?: any): any {\n const Ctor = this.constructor as new (e?: Iterable<[TK, TV] | TR>, o?: any) => any;\n return new Ctor(entries, options);\n }\n\n protected _rehashNoObj(): void {\n const fresh: Record<string, HashMapStoreItem<K, V>> = {};\n for (const { key, value } of Object.values(this._store)) {\n const sk = this._getNoObjKey(key);\n fresh[sk] = { key, value };\n }\n this._store = fresh;\n }\n\n protected *_getIterator(): IterableIterator<[K, V]> {\n for (const node of Object.values(this.store)) yield [node.key, node.value] as [K, V];\n for (const node of this.objMap) yield node as [K, V];\n }\n\n protected _isObjKey(key: any): key is object | ((...args: any[]) => any) {\n const keyType = typeof key;\n return (keyType === 'object' || keyType === 'function') && key !== null;\n }\n\n protected _getNoObjKey(key: K): string {\n const keyType = typeof key;\n\n let strKey: string;\n if (keyType !== 'string' && keyType !== 'number' && keyType !== 'symbol') {\n strKey = this._hashFn(key);\n } else {\n if (keyType === 'number') {\n strKey = <string>key;\n } else {\n strKey = <string>key;\n }\n }\n return strKey;\n }\n}\n\n/**\n * Hash-based map that preserves insertion order via a doubly-linked list.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n * @example examples will be generated by unit test\n */\nexport class LinkedHashMap<K = any, V = any, R = [K, V]> extends IterableEntryBase<K, V> {\n protected readonly _sentinel: HashMapLinkedNode<K, V | undefined>;\n\n /**\n * Create a LinkedHashMap and optionally bulk-insert entries.\n * @remarks Time O(N), Space O(N)\n * @param [entryOrRawElements] - Iterable of entries or raw elements to insert.\n * @param [options] - Options: hash functions and optional record-to-entry converter.\n * @returns New LinkedHashMap instance.\n */\n constructor(entryOrRawElements: Iterable<R | [K, V]> = [], options?: LinkedHashMapOptions<K, V, R>) {\n super();\n this._sentinel = <HashMapLinkedNode<K, V>>{};\n this._sentinel.prev = this._sentinel.next = this._head = this._tail = this._sentinel;\n\n if (options) {\n const { hashFn, objHashFn, toEntryFn } = options;\n if (hashFn) this._hashFn = hashFn;\n if (objHashFn) this._objHashFn = objHashFn;\n if (toEntryFn) this._toEntryFn = toEntryFn;\n }\n\n if (entryOrRawElements) this.setMany(entryOrRawElements);\n }\n\n protected _hashFn: (key: K) => string = (key: K) => String(key);\n get hashFn(): (key: K) => string {\n return this._hashFn;\n }\n\n protected _objHashFn: (key: K) => object = (key: K) => <object>key;\n\n /**\n * Get the hash function for object/weak keys.\n * @remarks Time O(1), Space O(1)\n * @returns Object-hash function.\n */\n get objHashFn(): (key: K) => object {\n return this._objHashFn;\n }\n\n protected _noObjMap: Record<string, HashMapLinkedNode<K, V | undefined>> = {};\n\n /**\n * Get the internal record for non-object keys.\n * @remarks Time O(1), Space O(1)\n * @returns Record of hash→node.\n */\n get noObjMap(): Record<string, HashMapLinkedNode<K, V | undefined>> {\n return this._noObjMap;\n }\n\n protected _objMap = new WeakMap<object, HashMapLinkedNode<K, V | undefined>>();\n get objMap(): WeakMap<object, HashMapLinkedNode<K, V | undefined>> {\n return this._objMap;\n }\n\n protected _head: HashMapLinkedNode<K, V | undefined>;\n\n /**\n * Get the head node (first entry) sentinel link.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or sentinel.\n */\n get head(): HashMapLinkedNode<K, V | undefined> {\n return this._head;\n }\n\n protected _tail: HashMapLinkedNode<K, V | undefined>;\n\n /**\n * Get the tail node (last entry) sentinel link.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or sentinel.\n */\n get tail(): HashMapLinkedNode<K, V | undefined> {\n return this._tail;\n }\n\n protected _toEntryFn?: (rawElement: R) => [K, V] = (rawElement: R) => {\n if (this.isEntry(rawElement)) {\n return rawElement;\n }\n throw new Error(\n 'If `entryOrRawElements` does not adhere to [key,value], provide `options.toEntryFn` to transform raw records.'\n );\n };\n get toEntryFn() {\n return this._toEntryFn;\n }\n\n protected _size = 0;\n get size() {\n return this._size;\n }\n\n /**\n * Get the first [key, value] pair.\n * @remarks Time O(1), Space O(1)\n * @returns First entry or undefined when empty.\n */\n get first() {\n if (this._size === 0) return;\n return <[K, V]>[this.head.key, this.head.value];\n }\n\n /**\n * Get the last [key, value] pair.\n * @remarks Time O(1), Space O(1)\n * @returns Last entry or undefined when empty.\n */\n get last() {\n if (this._size === 0) return;\n return <[K, V]>[this.tail.key, this.tail.value];\n }\n\n /**\n * Iterate from head → tail.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of [key, value].\n */\n *begin() {\n let node = this.head;\n while (node !== this._sentinel) {\n yield [node.key, node.value];\n node = node.next;\n }\n }\n\n /**\n * Iterate from tail → head.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of [key, value].\n */\n *reverseBegin() {\n let node = this.tail;\n while (node !== this._sentinel) {\n yield [node.key, node.value];\n node = node.prev;\n }\n }\n\n /**\n * Insert or replace a single entry; preserves insertion order.\n * @remarks Time O(1), Space O(1)\n * @param key - Key.\n * @param [value] - Value.\n * @returns True when the operation succeeds.\n */\n set(key: K, value?: V): boolean {\n let node: HashMapLinkedNode<K, V | undefined> | undefined;\n const isNewKey = !this.has(key);\n\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n node = this.objMap.get(hash);\n if (!node && isNewKey) {\n node = { key: <K>hash, value, prev: this.tail, next: this._sentinel };\n this.objMap.set(hash, node);\n } else if (node) {\n node.value = value;\n }\n } else {\n const hash = this._hashFn(key);\n node = this.noObjMap[hash];\n if (!node && isNewKey) {\n this.noObjMap[hash] = node = { key, value, prev: this.tail, next: this._sentinel };\n } else if (node) {\n node.value = value;\n }\n }\n\n if (node && isNewKey) {\n if (this._size === 0) {\n this._head = node;\n this._sentinel.next = node;\n } else {\n this.tail.next = node;\n node.prev = this.tail;\n }\n this._tail = node;\n this._sentinel.prev = node;\n this._size++;\n }\n\n return true;\n }\n\n setMany(entryOrRawElements: Iterable<R | [K, V]>): boolean[] {\n const results: boolean[] = [];\n for (const rawEle of entryOrRawElements) {\n let key: K | undefined, value: V | undefined;\n if (this.isEntry(rawEle)) [key, value] = rawEle;\n else if (this._toEntryFn) [key, value] = this._toEntryFn(rawEle);\n if (key !== undefined && value !== undefined) results.push(this.set(key, value));\n }\n return results;\n }\n\n override has(key: K): boolean {\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n return this.objMap.has(hash);\n }\n const hash = this._hashFn(key);\n return hash in this.noObjMap;\n }\n\n override get(key: K): V | undefined {\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n const node = this.objMap.get(hash);\n return node ? node.value : undefined;\n }\n const hash = this._hashFn(key);\n const node = this.noObjMap[hash];\n return node ? node.value : undefined;\n }\n\n /**\n * Get the value at a given index in insertion order.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Value at the index.\n */\n at(index: number): V | undefined {\n rangeCheck(index, 0, this._size - 1);\n let node = this.head;\n while (index--) node = node.next;\n return node.value;\n }\n\n delete(key: K): boolean {\n let node: HashMapLinkedNode<K, V | undefined> | undefined;\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n node = this.objMap.get(hash);\n if (!node) return false;\n this.objMap.delete(hash);\n } else {\n const hash = this._hashFn(key);\n node = this.noObjMap[hash];\n if (!node) return false;\n delete this.noObjMap[hash];\n }\n return this._deleteNode(node);\n }\n\n /**\n * Delete the first entry that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (key, value, index, map) → boolean to decide deletion.\n * @returns True if an entry was removed.\n */\n deleteWhere(predicate: (key: K, value: V | undefined, index: number, map: this) => boolean): boolean {\n let node = this._head;\n let i = 0;\n while (node !== this._sentinel) {\n const cur = node;\n node = node.next;\n if (predicate(cur.key as K, cur.value as V | undefined, i++, this)) {\n if (isWeakKey(cur.key as unknown as object)) {\n this._objMap.delete(cur.key as unknown as object);\n } else {\n const hash = this._hashFn(cur.key as K);\n delete this._noObjMap[hash];\n }\n return this._deleteNode(cur);\n }\n }\n return false;\n }\n\n /**\n * Delete the entry at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns True if removed.\n */\n deleteAt(index: number): boolean {\n rangeCheck(index, 0, this._size - 1);\n let node = this.head;\n while (index--) node = node.next;\n return this._deleteNode(node);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n isEntry(rawElement: any): rawElement is [K, V] {\n return Array.isArray(rawElement) && rawElement.length === 2;\n }\n\n clear(): void {\n this._noObjMap = {};\n this._size = 0;\n this._head = this._tail = this._sentinel.prev = this._sentinel.next = this._sentinel;\n }\n\n clone(): any {\n const opts = { hashFn: this._hashFn, objHashFn: this._objHashFn };\n return this._createLike<[K, V], [K, V], [K, V]>(this, opts);\n }\n\n filter(predicate: EntryCallback<K, V, boolean>, thisArg?: any): any {\n const out = this._createLike<K, V, [K, V]>();\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, value, key, index, this)) out.set(key, value);\n index++;\n }\n return out;\n }\n\n /**\n * Map each entry to a new [key, value] pair and preserve order.\n * @remarks Time O(N), Space O(N)\n * @template MK\n * @template MV\n * @param callback - Mapping function (key, value, index, map) → [newKey, newValue].\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new map of the same class with transformed entries.\n */\n map<MK, MV>(callback: EntryCallback<K, V, [MK, MV]>, thisArg?: any): any {\n const out = this._createLike<MK, MV, [MK, MV]>();\n let index = 0;\n for (const [key, value] of this) {\n const [newKey, newValue] = callback.call(thisArg, value, key, index, this);\n out.set(newKey, newValue);\n index++;\n }\n return out;\n }\n\n protected *_getIterator(): IterableIterator<[K, V]> {\n let node = this.head;\n while (node !== this._sentinel) {\n yield [node.key, node.value] as [K, V];\n node = node.next;\n }\n }\n\n protected _deleteNode(node: HashMapLinkedNode<K, V | undefined>): boolean {\n const { prev, next } = node;\n prev.next = next;\n next.prev = prev;\n\n if (node === this.head) this._head = next;\n if (node === this.tail) this._tail = prev;\n\n this._size -= 1;\n return true;\n }\n\n protected _createLike<TK = K, TV = V, TR = [TK, TV]>(entries: Iterable<[TK, TV] | TR> = [], options?: any): any {\n const Ctor = this.constructor as new (e?: Iterable<[TK, TV] | TR>, o?: any) => any;\n return new Ctor(entries, options);\n }\n}\n","import type { ElementCallback, LinearBaseOptions, ReduceLinearCallback } from '../../types';\nimport { IterableElementBase } from './iterable-element-base';\n\n/**\n * Singly-linked list node.\n * @template E - Element type.\n * @remarks Time O(1), Space O(1)\n */\nexport class LinkedListNode<E = any> {\n /**\n * Initialize a node.\n * @param value - Element value.\n * @remarks Time O(1), Space O(1)\n */\n constructor(value: E) {\n this._value = value;\n this._next = undefined;\n }\n\n protected _value: E;\n\n /**\n * Element payload getter.\n * @returns Element value.\n * @remarks Time O(1), Space O(1)\n */\n get value(): E {\n return this._value;\n }\n\n /**\n * Element payload setter.\n * @param value - New value.\n * @remarks Time O(1), Space O(1)\n */\n set value(value: E) {\n this._value = value;\n }\n\n protected _next: LinkedListNode<E> | undefined;\n\n /**\n * Next node getter.\n * @returns Next node or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n get next(): LinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Next node setter.\n * @param value - Next node or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n set next(value: LinkedListNode<E> | undefined) {\n this._next = value;\n }\n}\n\n/**\n * Abstract linear container with array-like utilities.\n * @template E - Element type.\n * @template R - Return type for mapped/derived views.\n * @template NODE - Linked node type used by some implementations.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class LinearBase<\n E,\n R = any,\n NODE extends LinkedListNode<E> = LinkedListNode<E>\n> extends IterableElementBase<E, R> {\n /**\n * Construct a linear container with runtime options.\n * @param options - `{ maxLen?, ... }` bounds/behavior options.\n * @remarks Time O(1), Space O(1)\n */\n protected constructor(options?: LinearBaseOptions<E, R>) {\n super(options);\n if (options) {\n const { maxLen } = options;\n if (typeof maxLen === 'number' && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;\n }\n }\n\n /**\n * Element count.\n * @returns Number of elements.\n * @remarks Time O(1), Space O(1)\n */\n abstract get length(): number;\n\n protected _maxLen: number = -1;\n\n /**\n * Upper bound for length (if positive), or `-1` when unbounded.\n * @returns Maximum allowed length.\n * @remarks Time O(1), Space O(1)\n */\n get maxLen() {\n return this._maxLen;\n }\n\n /**\n * First index of a value from the left.\n * @param searchElement - Value to match.\n * @param fromIndex - Start position (supports negative index).\n * @returns Index or `-1` if not found.\n * @remarks Time O(n), Space O(1)\n */\n indexOf(searchElement: E, fromIndex: number = 0): number {\n if (this.length === 0) return -1;\n if (fromIndex < 0) fromIndex = this.length + fromIndex;\n if (fromIndex < 0) fromIndex = 0;\n\n for (let i = fromIndex; i < this.length; i++) {\n const element = this.at(i);\n if (element === searchElement) return i;\n }\n\n return -1;\n }\n\n /**\n * Last index of a value from the right.\n * @param searchElement - Value to match.\n * @param fromIndex - Start position (supports negative index).\n * @returns Index or `-1` if not found.\n * @remarks Time O(n), Space O(1)\n */\n lastIndexOf(searchElement: E, fromIndex: number = this.length - 1): number {\n if (this.length === 0) return -1;\n if (fromIndex >= this.length) fromIndex = this.length - 1;\n if (fromIndex < 0) fromIndex = this.length + fromIndex;\n\n for (let i = fromIndex; i >= 0; i--) {\n const element = this.at(i);\n if (element === searchElement) return i;\n }\n\n return -1;\n }\n\n /**\n * Find the first index matching a predicate.\n * @param predicate - `(element, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n findIndex(predicate: ElementCallback<E, R, boolean>, thisArg?: any): number {\n for (let i = 0; i < this.length; i++) {\n const item = this.at(i);\n if (item !== undefined && predicate.call(thisArg, item, i, this)) return i;\n }\n return -1;\n }\n\n /**\n * Concatenate multiple containers of the same species.\n * @param items - Other lists to append.\n * @returns New container with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n concat(...items: this[]): this;\n\n /**\n * Concatenate elements and/or containers.\n * @param items - Elements or other containers.\n * @returns New container with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n concat(...items: (E | this)[]): this {\n const newList = this.clone();\n\n for (const item of items) {\n if (item instanceof LinearBase) {\n newList.pushMany(item);\n } else {\n newList.push(item);\n }\n }\n\n return newList;\n }\n\n /**\n * In-place stable order via array sort semantics.\n * @param compareFn - Comparator `(a, b) => number`.\n * @returns This container.\n * @remarks Time O(n log n), Space O(n) (materializes to array temporarily)\n */\n sort(compareFn?: (a: E, b: E) => number): this {\n const arr = this.toArray();\n arr.sort(compareFn);\n this.clear();\n for (const item of arr) this.push(item);\n return this;\n }\n\n /**\n * Remove and/or insert elements at a position (array-compatible).\n * @param start - Start index (supports negative index).\n * @param deleteCount - How many to remove.\n * @param items - Elements to insert.\n * @returns Removed elements as a new list (`this` type).\n * @remarks Time O(n + m), Space O(min(n, m)) where `m = items.length`\n */\n splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n const removedList = this._createInstance();\n\n start = start < 0 ? this.length + start : start;\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));\n\n for (let i = 0; i < deleteCount; i++) {\n const removed = this.deleteAt(start);\n if (removed !== undefined) {\n removedList.push(removed);\n }\n }\n\n for (let i = 0; i < items.length; i++) {\n this.addAt(start + i, items[i]);\n }\n\n return removedList;\n }\n\n /**\n * Join all elements into a string.\n * @param separator - Separator string.\n * @returns Concatenated string.\n * @remarks Time O(n), Space O(n)\n */\n join(separator: string = ','): string {\n return this.toArray().join(separator);\n }\n\n /**\n * Snapshot elements into a reversed array.\n * @returns New reversed array.\n * @remarks Time O(n), Space O(n)\n */\n toReversedArray(): E[] {\n const array: E[] = [];\n for (let i = this.length - 1; i >= 0; i--) {\n array.push(this.at(i)!);\n }\n return array;\n }\n\n reduceRight(callbackfn: ReduceLinearCallback<E>): E;\n\n reduceRight(callbackfn: ReduceLinearCallback<E>, initialValue: E): E;\n\n /**\n * Right-to-left reduction over elements.\n * @param callbackfn - `(acc, element, index, self) => acc`.\n * @param initialValue - Initial accumulator (optional generic overloads supported).\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue: U): U;\n\n reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue?: U): U {\n let accumulator = initialValue ?? (0 as U);\n for (let i = this.length - 1; i >= 0; i--) {\n accumulator = callbackfn(accumulator, this.at(i)!, i, this);\n }\n return accumulator;\n }\n\n /**\n * Create a shallow copy of a subrange.\n * @param start - Inclusive start (supports negative index).\n * @param end - Exclusive end (supports negative index).\n * @returns New list with the range (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n slice(start: number = 0, end: number = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n const newList = this._createInstance();\n for (let i = start; i < end; i++) {\n newList.push(this.at(i)!);\n }\n return newList;\n }\n\n /**\n * Fill a range with a value.\n * @param value - Value to set.\n * @param start - Inclusive start.\n * @param end - Exclusive end.\n * @returns This list.\n * @remarks Time O(n), Space O(1)\n */\n fill(value: E, start = 0, end = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n if (start < 0) start = 0;\n if (end > this.length) end = this.length;\n if (start >= end) return this;\n\n for (let i = start; i < end; i++) {\n this.setAt(i, value);\n }\n\n return this;\n }\n\n /**\n * Set the value at an index.\n * @param index - Position (0-based).\n * @param value - New value.\n * @returns `true` if updated.\n * @remarks Time O(1) typical, Space O(1)\n */\n abstract setAt(index: number, value: E): boolean;\n\n /**\n * Deep clone while preserving concrete subtype.\n * @returns New list of the same species (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n abstract override clone(): this;\n\n /**\n * Reverse the order of elements in-place (or equivalent).\n * @returns This list.\n * @remarks Time O(n), Space O(1)\n */\n abstract reverse(): this;\n\n /**\n * Append one element or node to the tail.\n * @param elementOrNode - Element or node.\n * @returns `true` if appended.\n * @remarks Time O(1) amortized typical, Space O(1)\n */\n abstract push(elementOrNode: E | NODE): boolean;\n\n /**\n * Append many elements/nodes at once.\n * @param elements - Iterable of elements or nodes.\n * @returns Array of booleans indicating append success.\n * @remarks Time O(n), Space O(1)\n */\n abstract pushMany(elements: Iterable<E> | Iterable<R> | Iterable<NODE>): boolean[];\n\n /**\n * Remove one element or node if present.\n * @param elementOrNode - Element or node to delete.\n * @returns `true` if removed.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract delete(elementOrNode: E | NODE | undefined): boolean;\n\n /**\n * Get element at an index.\n * @param index - Position (0-based).\n * @returns Element or `undefined`.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract at(index: number): E | undefined;\n\n /**\n * Remove element at a position.\n * @param pos - Position (0-based).\n * @returns Removed element or `undefined`.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract deleteAt(pos: number): E | undefined;\n\n /**\n * Insert an element/node at a position.\n * @param index - Position (0-based).\n * @param newElementOrNode - Element or node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract addAt(index: number, newElementOrNode: E | NODE): boolean;\n\n /**\n * Create an empty list of the same species.\n * @param options - Runtime options to carry.\n * @returns Empty list (`this` type).\n * @remarks Time O(1), Space O(1)\n */\n protected abstract _createInstance(options?: LinearBaseOptions<E, R>): this;\n\n /**\n * Reverse-direction iterator over elements.\n * @returns Iterator of elements from tail to head.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getReverseIterator(...args: any[]): IterableIterator<E>;\n}\n\n/**\n * Linked-list specialized linear container.\n * @template E - Element type.\n * @template R - Return type for mapped/derived views.\n * @template NODE - Linked node type.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class LinearLinkedBase<\n E,\n R = any,\n NODE extends LinkedListNode<E> = LinkedListNode<E>\n> extends LinearBase<E, R, NODE> {\n protected constructor(options?: LinearBaseOptions<E, R>) {\n super(options);\n if (options) {\n const { maxLen } = options;\n if (typeof maxLen === 'number' && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;\n }\n }\n\n /**\n * Linked-list optimized `indexOf` (forwards scan).\n * @param searchElement - Value to match.\n * @param fromIndex - Start position.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n override indexOf(searchElement: E, fromIndex: number = 0): number {\n const iterator = this._getIterator();\n let current = iterator.next();\n\n let index = 0;\n while (index < fromIndex) {\n current = iterator.next();\n index++;\n }\n\n while (!current.done) {\n if (current.value === searchElement) return index;\n current = iterator.next();\n index++;\n }\n\n return -1;\n }\n\n /**\n * Linked-list optimized `lastIndexOf` (reverse scan).\n * @param searchElement - Value to match.\n * @param fromIndex - Start position.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n override lastIndexOf(searchElement: E, fromIndex: number = this.length - 1): number {\n const iterator = this._getReverseIterator();\n let current = iterator.next();\n\n let index = this.length - 1;\n while (index > fromIndex) {\n current = iterator.next();\n index--;\n }\n\n while (!current.done) {\n if (current.value === searchElement) return index;\n current = iterator.next();\n index--;\n }\n\n return -1;\n }\n\n /**\n * Concatenate lists/elements preserving order.\n * @param items - Elements or `LinearBase` instances.\n * @returns New list with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n override concat(...items: LinearBase<E, R>[]): this;\n\n override concat(...items: (E | LinearBase<E, R>)[]): this {\n const newList = this.clone();\n\n for (const item of items) {\n if (item instanceof LinearBase) {\n newList.pushMany(item);\n } else {\n newList.push(item);\n }\n }\n\n return newList;\n }\n\n /**\n * Slice via forward iteration (no random access required).\n * @param start - Inclusive start (supports negative index).\n * @param end - Exclusive end (supports negative index).\n * @returns New list (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n override slice(start: number = 0, end: number = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n const newList = this._createInstance();\n const iterator = this._getIterator();\n let current = iterator.next();\n let c = 0;\n while (c < start) {\n current = iterator.next();\n c++;\n }\n for (let i = start; i < end; i++) {\n newList.push(current.value);\n current = iterator.next();\n }\n\n return newList;\n }\n\n /**\n * Splice by walking node iterators from the start index.\n * @param start - Start index.\n * @param deleteCount - How many elements to remove.\n * @param items - Elements to insert after the splice point.\n * @returns Removed elements as a new list (`this` type).\n * @remarks Time O(n + m), Space O(min(n, m)) where `m = items.length`\n */\n override splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n const removedList = this._createInstance();\n\n start = start < 0 ? this.length + start : start;\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, deleteCount);\n\n let currentIndex = 0;\n let currentNode: NODE | undefined = undefined;\n let previousNode: NODE | undefined = undefined;\n\n const iterator = this._getNodeIterator();\n for (const node of iterator) {\n if (currentIndex === start) {\n currentNode = node;\n break;\n }\n previousNode = node;\n currentIndex++;\n }\n\n for (let i = 0; i < deleteCount && currentNode; i++) {\n removedList.push(currentNode.value);\n const nextNode = currentNode.next;\n this.delete(currentNode);\n currentNode = nextNode as NODE;\n }\n\n for (let i = 0; i < items.length; i++) {\n if (previousNode) {\n this.addAfter(previousNode, items[i]);\n previousNode = previousNode.next as NODE;\n } else {\n this.addAt(0, items[i]);\n previousNode = this._getNodeIterator().next().value;\n }\n }\n\n return removedList;\n }\n\n override reduceRight(callbackfn: ReduceLinearCallback<E>): E;\n\n override reduceRight(callbackfn: ReduceLinearCallback<E>, initialValue: E): E;\n\n /**\n * Right-to-left reduction using reverse iterator.\n * @param callbackfn - `(acc, element, index, self) => acc`.\n * @param initialValue - Initial accumulator.\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n override reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue: U): U;\n\n override reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue?: U): U {\n let accumulator = initialValue ?? (0 as U);\n let index = this.length - 1;\n for (const item of this._getReverseIterator()) {\n accumulator = callbackfn(accumulator, item, index--, this);\n }\n return accumulator;\n }\n\n /**\n * Delete by element or node in a linked list.\n * @param elementOrNode - Element or node.\n * @returns `true` if removed.\n * @remarks Time O(1)~O(n) depending on availability of links, Space O(1)\n */\n abstract override delete(elementOrNode: E | NODE | undefined): boolean;\n\n /**\n * Insert new element/node before an existing node.\n * @param existingElementOrNode - Reference element/node.\n * @param newElementOrNode - Element/node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on reference access, Space O(1)\n */\n abstract addBefore(existingElementOrNode: E | NODE, newElementOrNode: E | NODE): boolean;\n\n /**\n * Insert new element/node after an existing node.\n * @param existingElementOrNode - Reference element/node.\n * @param newElementOrNode - Element/node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on reference access, Space O(1)\n */\n abstract addAfter(existingElementOrNode: E | NODE, newElementOrNode: E | NODE): boolean;\n\n /**\n * Node at index (for random-access emulation).\n * @param index - Position (0-based).\n * @returns Node or `undefined`.\n * @remarks Time O(n), Space O(1)\n */\n abstract getNodeAt(index: number): NODE | undefined;\n\n /**\n * Iterate linked nodes from head to tail.\n * @returns Iterator over nodes.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getNodeIterator(...args: any[]): IterableIterator<NODE>;\n\n /**\n * Get previous node of a given node.\n * @param node - Current node.\n * @returns Previous node or `undefined`.\n * @remarks Time O(1)~O(n) depending on list variant (singly vs doubly), Space O(1)\n */\n protected abstract _getPrevNode(node: NODE): NODE | undefined;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, SinglyLinkedListOptions } from '../../types';\nimport { LinearLinkedBase, LinkedListNode } from '../base/linear-base';\n\n/**\n * Node of a singly linked list; stores value and the next link.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class SinglyLinkedListNode<E = any> extends LinkedListNode<E> {\n /**\n * Create a list node.\n * @remarks Time O(1), Space O(1)\n * @param value - Element value to store.\n * @returns New node instance.\n */\n\n constructor(value: E) {\n super(value);\n this._value = value;\n this._next = undefined;\n }\n\n protected override _next: SinglyLinkedListNode<E> | undefined;\n\n /**\n * Get the next node.\n * @remarks Time O(1), Space O(1)\n * @returns Next node or undefined.\n */\n\n override get next(): SinglyLinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Set the next node.\n * @remarks Time O(1), Space O(1)\n * @param value - Next node or undefined.\n * @returns void\n */\n\n override set next(value: SinglyLinkedListNode<E> | undefined) {\n this._next = value;\n }\n}\n\n/**\n * Singly linked list with O(1) push/pop-like ends operations and linear scans.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.\n * 2. Bidirectional Traversal: Unlike doubly linked lists, singly linked lists can be easily traversed forwards but not backwards.\n * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.\n * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.\n * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).\n * @example\n * // basic SinglyLinkedList creation and push operation\n * // Create a simple SinglyLinkedList with initial values\n * const list = new SinglyLinkedList([1, 2, 3, 4, 5]);\n *\n * // Verify the list maintains insertion order\n * console.log([...list]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(list.length); // 5;\n *\n * // Push a new element to the end\n * list.push(6);\n * console.log(list.length); // 6;\n * console.log([...list]); // [1, 2, 3, 4, 5, 6];\n * @example\n * // SinglyLinkedList pop and shift operations\n * const list = new SinglyLinkedList<number>([10, 20, 30, 40, 50]);\n *\n * // Pop removes from the end\n * const last = list.pop();\n * console.log(last); // 50;\n *\n * // Shift removes from the beginning\n * const first = list.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements\n * console.log([...list]); // [20, 30, 40];\n * console.log(list.length); // 3;\n * @example\n * // SinglyLinkedList unshift and forward traversal\n * const list = new SinglyLinkedList<number>([20, 30, 40]);\n *\n * // Unshift adds to the beginning\n * list.unshift(10);\n * console.log([...list]); // [10, 20, 30, 40];\n *\n * // Access elements (forward traversal only for singly linked)\n * const second = list.at(1);\n * console.log(second); // 20;\n *\n * // SinglyLinkedList allows forward iteration only\n * const elements: number[] = [];\n * for (const item of list) {\n * elements.push(item);\n * }\n * console.log(elements); // [10, 20, 30, 40];\n *\n * console.log(list.length); // 4;\n * @example\n * // SinglyLinkedList filter and map operations\n * const list = new SinglyLinkedList<number>([1, 2, 3, 4, 5]);\n *\n * // Filter even numbers\n * const filtered = list.filter(value => value % 2 === 0);\n * console.log(filtered.length); // 2;\n *\n * // Map to double values\n * const doubled = list.map(value => value * 2);\n * console.log(doubled.length); // 5;\n *\n * // Use reduce to sum\n * const sum = list.reduce((acc, value) => acc + value, 0);\n * console.log(sum); // 15;\n * @example\n * // SinglyLinkedList for sequentially processed data stream\n * interface LogEntry {\n * timestamp: number;\n * level: 'INFO' | 'WARN' | 'ERROR';\n * message: string;\n * }\n *\n * // SinglyLinkedList is ideal for sequential processing where you only need forward iteration\n * // O(1) insertion/deletion at head, O(n) for tail operations\n * const logStream = new SinglyLinkedList<LogEntry>();\n *\n * // Simulate incoming log entries\n * const entries: LogEntry[] = [\n * { timestamp: 1000, level: 'INFO', message: 'Server started' },\n * { timestamp: 1100, level: 'WARN', message: 'Memory usage high' },\n * { timestamp: 1200, level: 'ERROR', message: 'Connection failed' },\n * { timestamp: 1300, level: 'INFO', message: 'Connection restored' }\n * ];\n *\n * // Add entries to the stream\n * for (const entry of entries) {\n * logStream.push(entry);\n * }\n *\n * console.log(logStream.length); // 4;\n *\n * // Process logs sequentially (only forward iteration needed)\n * const processedLogs: string[] = [];\n * for (const log of logStream) {\n * processedLogs.push(`[${log.level}] ${log.message}`);\n * }\n *\n * console.log(processedLogs); // [\n * // '[INFO] Server started',\n * // '[WARN] Memory usage high',\n * // '[ERROR] Connection failed',\n * // '[INFO] Connection restored'\n * // ];\n *\n * // Get first log (O(1) - direct head access)\n * const firstLog = logStream.at(0);\n * console.log(firstLog?.message); // 'Server started';\n *\n * // Remove oldest log (O(1) operation at head)\n * const removed = logStream.shift();\n * console.log(removed?.message); // 'Server started';\n * console.log(logStream.length); // 3;\n *\n * // Remaining logs still maintain order for sequential processing\n * console.log(logStream.length); // 3;\n * @example\n * // implementation of a basic text editor\n * class TextEditor {\n * private content: SinglyLinkedList<string>;\n * private cursorIndex: number;\n * private undoStack: Stack<{ operation: string; data?: any }>;\n *\n * constructor() {\n * this.content = new SinglyLinkedList<string>();\n * this.cursorIndex = 0; // Cursor starts at the beginning\n * this.undoStack = new Stack<{ operation: string; data?: any }>(); // Stack to keep track of operations for undo\n * }\n *\n * insert(char: string) {\n * this.content.addAt(this.cursorIndex, char);\n * this.cursorIndex++;\n * this.undoStack.push({ operation: 'insert', data: { index: this.cursorIndex - 1 } });\n * }\n *\n * delete() {\n * if (this.cursorIndex === 0) return; // Nothing to delete\n * const deleted = this.content.deleteAt(this.cursorIndex - 1);\n * this.cursorIndex--;\n * this.undoStack.push({ operation: 'delete', data: { index: this.cursorIndex, char: deleted } });\n * }\n *\n * moveCursor(index: number) {\n * this.cursorIndex = Math.max(0, Math.min(index, this.content.length));\n * }\n *\n * undo() {\n * if (this.undoStack.size === 0) return; // No operations to undo\n * const lastAction = this.undoStack.pop();\n *\n * if (lastAction!.operation === 'insert') {\n * this.content.deleteAt(lastAction!.data.index);\n * this.cursorIndex = lastAction!.data.index;\n * } else if (lastAction!.operation === 'delete') {\n * this.content.addAt(lastAction!.data.index, lastAction!.data.char);\n * this.cursorIndex = lastAction!.data.index + 1;\n * }\n * }\n *\n * getText(): string {\n * return [...this.content].join('');\n * }\n * }\n *\n * // Example Usage\n * const editor = new TextEditor();\n * editor.insert('H');\n * editor.insert('e');\n * editor.insert('l');\n * editor.insert('l');\n * editor.insert('o');\n * console.log(editor.getText()); // 'Hello'; // Output: \"Hello\"\n *\n * editor.delete();\n * console.log(editor.getText()); // 'Hell'; // Output: \"Hell\"\n *\n * editor.undo();\n * console.log(editor.getText()); // 'Hello'; // Output: \"Hello\"\n *\n * editor.moveCursor(1);\n * editor.insert('a');\n * console.log(editor.getText()); // 'Haello';\n */\nexport class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, SinglyLinkedListNode<E>> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a SinglyLinkedList and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @param [options] - Options such as maxLen and toElementFn.\n * @returns New SinglyLinkedList instance.\n */\n\n constructor(\n elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>> = [],\n options?: SinglyLinkedListOptions<E, R>\n ) {\n super(options);\n this.pushMany(elements);\n }\n\n protected _head: SinglyLinkedListNode<E> | undefined;\n\n /**\n * Get the head node.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or undefined.\n */\n\n get head(): SinglyLinkedListNode<E> | undefined {\n return this._head;\n }\n\n protected _tail: SinglyLinkedListNode<E> | undefined;\n\n /**\n * Get the tail node.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or undefined.\n */\n\n get tail(): SinglyLinkedListNode<E> | undefined {\n return this._tail;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this._length;\n }\n\n /**\n * Get the first element value.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n return this.head?.value;\n }\n\n /**\n * Get the last element value.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n return this.tail?.value;\n }\n\n /**\n * Create a new list from an iterable of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @template S\n * @param this - The constructor (subclass) to instantiate.\n * @param data - Iterable of elements to insert.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new list populated with the iterable's elements.\n */\n\n static from<E, R = any, S extends SinglyLinkedList<E, R> = SinglyLinkedList<E, R>>(\n this: new (\n elements?: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>,\n options?: SinglyLinkedListOptions<E, R>\n ) => S,\n data: Iterable<E>,\n options?: SinglyLinkedListOptions<E, R>\n ): S {\n const list = new this([], options);\n for (const x of data) list.push(x);\n return list;\n }\n\n /**\n * Append an element/node to the tail.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to append.\n * @returns True when appended.\n */\n\n push(elementOrNode: E | SinglyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = this._tail = newNode;\n } else {\n this.tail!.next = newNode;\n this._tail = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the tail element.\n * @remarks Time O(N), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (!this.head) return undefined;\n if (this.head === this.tail) {\n const value = this.head.value;\n this._head = undefined;\n this._tail = undefined;\n this._length--;\n return value;\n }\n let current = this.head;\n while (current.next !== this.tail) current = current.next!;\n const value = this.tail!.value;\n current.next = undefined;\n this._tail = current;\n this._length--;\n return value;\n }\n\n /**\n * Remove and return the head element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (!this.head) return undefined;\n const removed = this.head;\n this._head = this.head.next;\n if (!this._head) this._tail = undefined;\n this._length--;\n return removed.value;\n }\n\n /**\n * Prepend an element/node to the head.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to prepend.\n * @returns True when prepended.\n */\n\n unshift(elementOrNode: E | SinglyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = this._tail = newNode;\n } else {\n newNode.next = this.head;\n this._head = newNode;\n }\n this._length++;\n return true;\n }\n\n /**\n * Append a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E | SinglyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.unshift(this.toElementFn(el as R)));\n else ans.push(this.unshift(el as E | SinglyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Find the first value matching a predicate (by node).\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate to match.\n * @returns Matched value or undefined.\n */\n\n search(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Get the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current!.value;\n }\n\n /**\n * Type guard: check whether the input is a SinglyLinkedListNode.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns True if the value is a SinglyLinkedListNode.\n */\n\n isNode(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is SinglyLinkedListNode<E> {\n return elementNodeOrPredicate instanceof SinglyLinkedListNode;\n }\n\n /**\n * Get the node reference at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Node or undefined.\n */\n\n getNodeAt(index: number): SinglyLinkedListNode<E> | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current;\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n if (index === 0) return this.shift();\n const targetNode = this.getNodeAt(index)!;\n const prevNode = this._getPrevNode(targetNode)!;\n const value = targetNode.value;\n prevNode.next = targetNode.next;\n if (targetNode === this.tail) this._tail = prevNode;\n this._length--;\n return value;\n }\n\n /**\n * Delete the first match by value/node.\n * @remarks Time O(N), Space O(1)\n * @param [elementOrNode] - Element or node to remove; if omitted/undefined, nothing happens.\n * @returns True if removed.\n */\n\n delete(elementOrNode: E | SinglyLinkedListNode<E> | undefined): boolean {\n if (elementOrNode === undefined || !this.head) return false;\n const node = this.isNode(elementOrNode) ? elementOrNode : this.getNode(elementOrNode);\n if (!node) return false;\n const prevNode = this._getPrevNode(node);\n\n if (!prevNode) {\n this._head = node.next;\n if (node === this.tail) this._tail = undefined;\n } else {\n prevNode.next = node.next;\n if (node === this.tail) this._tail = prevNode;\n }\n this._length--;\n return true;\n }\n\n /**\n * Insert a new element/node at an index, shifting following nodes.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElementOrNode: E | SinglyLinkedListNode<E>): boolean {\n if (index < 0 || index > this._length) return false;\n if (index === 0) return this.unshift(newElementOrNode);\n if (index === this._length) return this.push(newElementOrNode);\n const newNode = this._ensureNode(newElementOrNode);\n const prevNode = this.getNodeAt(index - 1)!;\n newNode.next = prevNode.next;\n prevNode.next = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Set the element value at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param value - New value.\n * @returns True if updated.\n */\n\n setAt(index: number, value: E): boolean {\n const node = this.getNodeAt(index);\n if (!node) return false;\n node.value = value;\n return true;\n }\n\n /**\n * Check whether the list is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this._length === 0;\n }\n\n /**\n * Remove all nodes and reset length.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n }\n\n /**\n * Reverse the list in place.\n * @remarks Time O(N), Space O(1)\n * @returns This list.\n */\n\n reverse(): this {\n if (!this.head || this.head === this.tail) return this;\n let prev: SinglyLinkedListNode<E> | undefined;\n let current: SinglyLinkedListNode<E> | undefined = this.head;\n let next: SinglyLinkedListNode<E> | undefined;\n while (current) {\n next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n [this._head, this._tail] = [this.tail!, this.head!];\n return this;\n }\n\n /**\n * Find a node by value, reference, or predicate.\n * @remarks Time O(N), Space O(1)\n * @param [elementNodeOrPredicate] - Element, node, or node predicate to match.\n * @returns Matching node or undefined.\n */\n\n getNode(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean) | undefined\n ): SinglyLinkedListNode<E> | undefined {\n if (elementNodeOrPredicate === undefined) return;\n if (this.isNode(elementNodeOrPredicate)) return elementNodeOrPredicate;\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Insert a new element/node before an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addBefore(\n existingElementOrNode: E | SinglyLinkedListNode<E>,\n newElementOrNode: E | SinglyLinkedListNode<E>\n ): boolean {\n const existingNode = this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n const prevNode = this._getPrevNode(existingNode);\n const newNode = this._ensureNode(newElementOrNode);\n\n if (!prevNode) {\n newNode.next = this._head;\n this._head = newNode;\n if (!this._tail) this._tail = newNode;\n this._length++;\n } else {\n prevNode.next = newNode;\n newNode.next = existingNode;\n this._length++;\n }\n return true;\n }\n\n /**\n * Insert a new element/node after an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAfter(existingElementOrNode: E | SinglyLinkedListNode<E>, newElementOrNode: E | SinglyLinkedListNode<E>): boolean {\n const existingNode = this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n const newNode = this._ensureNode(newElementOrNode);\n newNode.next = existingNode.next;\n existingNode.next = newNode;\n if (existingNode === this.tail) this._tail = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Remove and/or insert elements at a position (array-like behavior).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default 0).\n * @param [items] - Elements to insert after `start`.\n * @returns A new list containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount = 0, ...items: E[]): this {\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, deleteCount);\n\n const removedList = this._createInstance();\n\n const prevNode = start === 0 ? undefined : this.getNodeAt(start - 1);\n let cur = prevNode ? prevNode.next : this.head;\n\n let removedCount = 0;\n while (removedCount < deleteCount && cur) {\n removedList.push(cur.value);\n cur = cur.next;\n removedCount++;\n }\n const afterNode = cur;\n\n if (prevNode) {\n prevNode.next = afterNode;\n } else {\n this._head = afterNode;\n }\n if (!afterNode) this._tail = prevNode;\n\n if (items.length > 0) {\n let firstInserted: SinglyLinkedListNode<E> | undefined;\n let lastInserted: SinglyLinkedListNode<E> | undefined;\n for (const it of items) {\n const node = this._ensureNode(it);\n if (!firstInserted) firstInserted = node;\n if (lastInserted) lastInserted.next = node;\n lastInserted = node;\n }\n if (prevNode) prevNode.next = firstInserted!;\n else this._head = firstInserted!;\n\n lastInserted!.next = afterNode;\n if (!afterNode) this._tail = lastInserted!;\n }\n\n this._length += items.length - removedCount;\n if (this._length === 0) {\n this._head = undefined;\n this._tail = undefined;\n }\n\n return removedList as unknown as this;\n }\n\n /**\n * Count how many nodes match a value/node/predicate.\n * @remarks Time O(N), Space O(1)\n * @param elementOrNode - Element, node, or node predicate to match.\n * @returns Number of matches in the list.\n */\n\n countOccurrences(elementOrNode: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): number {\n const predicate = elementOrPredicate(elementOrNode, this._equals);\n let count = 0;\n let current = this.head;\n while (current) {\n if (predicate(current)) count++;\n current = current.next;\n }\n return count;\n }\n\n /**\n * Set the equality comparator used to compare values.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This list.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Delete the first node whose value matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Predicate (value, index, list) → boolean to decide deletion.\n * @returns True if a node was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, list: this) => boolean): boolean {\n let prev: SinglyLinkedListNode<E> | undefined;\n let current = this.head;\n let i = 0;\n while (current) {\n if (predicate(current.value, i++, this)) {\n if (!prev) {\n this._head = current.next;\n if (current === this._tail) this._tail = undefined;\n } else {\n prev.next = current.next;\n if (current === this._tail) this._tail = prev;\n }\n this._length--;\n return true;\n }\n prev = current;\n current = current.next;\n }\n return false;\n }\n\n /**\n * Deep clone this list (values are copied by reference).\n * @remarks Time O(N), Space O(N)\n * @returns A new list with the same element sequence.\n */\n\n clone(): this {\n const out = this._createInstance();\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Predicate (value, index, list) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with kept values.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance();\n let index = 0;\n for (const value of this) if (callback.call(thisArg, value, index++, this)) out.push(value);\n return out;\n }\n\n /**\n * Map values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, list) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance();\n let index = 0;\n for (const value of this) {\n const mv = thisArg === undefined ? callback(value, index++, this) : callback.call(thisArg, value, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new list (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, list) → newElement.\n * @param [options] - Options for the output list (e.g., maxLen, toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new SinglyLinkedList with mapped values.\n */\n\n map<EM, RM = any>(\n callback: ElementCallback<E, R, EM>,\n options?: SinglyLinkedListOptions<EM, RM>,\n thisArg?: any\n ): SinglyLinkedList<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}), maxLen: this._maxLen as number });\n let index = 0;\n for (const value of this) out.push(callback.call(thisArg, value, index++, this));\n return out;\n }\n\n /**\n * (Protected) Create a node from a value.\n * @remarks Time O(1), Space O(1)\n * @param value - Value to wrap in a node.\n * @returns A new SinglyLinkedListNode instance.\n */\n\n protected createNode(value: E): SinglyLinkedListNode<E> {\n return new SinglyLinkedListNode<E>(value);\n }\n\n /**\n * (Protected) Check if input is a node predicate function.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate.\n * @returns True if input is a predicate function.\n */\n\n protected _isPredicate(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is (node: SinglyLinkedListNode<E>) => boolean {\n return typeof elementNodeOrPredicate === 'function';\n }\n\n /**\n * (Protected) Normalize input into a node instance.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node.\n * @returns A SinglyLinkedListNode for the provided input.\n */\n\n protected _ensureNode(elementOrNode: E | SinglyLinkedListNode<E>) {\n if (this.isNode(elementOrNode)) return elementOrNode;\n return this.createNode(elementOrNode);\n }\n\n /**\n * (Protected) Normalize input into a node predicate.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns A predicate taking a node and returning true/false.\n */\n\n protected _ensurePredicate(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ) {\n if (this.isNode(elementNodeOrPredicate)) return (node: SinglyLinkedListNode<E>) => node === elementNodeOrPredicate;\n if (this._isPredicate(elementNodeOrPredicate)) return elementNodeOrPredicate;\n const value = elementNodeOrPredicate as E;\n return (node: SinglyLinkedListNode<E>) => this._equals(node.value, value);\n }\n\n /**\n * (Protected) Get the previous node of a given node.\n * @remarks Time O(N), Space O(1)\n * @param node - A node in the list.\n * @returns Previous node or undefined.\n */\n\n protected _getPrevNode(node: SinglyLinkedListNode<E>): SinglyLinkedListNode<E> | undefined {\n if (!this.head || this.head === node) return undefined;\n let current = this.head;\n while (current.next && current.next !== node) current = current.next;\n return current.next === node ? current : undefined;\n }\n\n /**\n * (Protected) Iterate values from head to tail.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of values (E).\n */\n\n protected *_getIterator(): IterableIterator<E> {\n let current = this.head;\n while (current) {\n yield current.value;\n current = current.next;\n }\n }\n\n /**\n * (Protected) Iterate values from tail to head.\n * @remarks Time O(N), Space O(N)\n * @returns Iterator of values (E).\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n const reversedArr = [...this].reverse();\n for (const item of reversedArr) yield item;\n }\n\n /**\n * (Protected) Iterate nodes from head to tail.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of nodes.\n */\n\n protected *_getNodeIterator(): IterableIterator<SinglyLinkedListNode<E>> {\n let current = this.head;\n while (current) {\n yield current;\n current = current.next;\n }\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind list instance.\n */\n\n protected _createInstance(options?: SinglyLinkedListOptions<E, R>): this {\n const Ctor: any = this.constructor;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new list.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind SinglyLinkedList instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> | Iterable<SinglyLinkedListNode<EM>> = [],\n options?: SinglyLinkedListOptions<EM, RM>\n ): SinglyLinkedList<EM, RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as SinglyLinkedList<EM, RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind list instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind SinglyLinkedList instance.\n */\n\n protected _spawnLike<EM, RM>(options?: SinglyLinkedListOptions<EM, RM>): SinglyLinkedList<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\nfunction elementOrPredicate<E>(\n input: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean),\n equals: (a: E, b: E) => boolean\n) {\n if (input instanceof SinglyLinkedListNode) return (node: SinglyLinkedListNode<E>) => node === input;\n if (typeof input === 'function') return input as (node: SinglyLinkedListNode<E>) => boolean;\n const value = input as E;\n return (node: SinglyLinkedListNode<E>) => equals(node.value, value);\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { DoublyLinkedListOptions, ElementCallback, LinearBaseOptions } from '../../types';\nimport { LinearLinkedBase, LinkedListNode } from '../base/linear-base';\n\n/**\n * Node of a doubly linked list; stores value and prev/next links.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class DoublyLinkedListNode<E = any> extends LinkedListNode<E> {\n /**\n * Create a node.\n * @remarks Time O(1), Space O(1)\n * @param value - Element value to store.\n * @returns New node instance.\n */\n\n constructor(value: E) {\n super(value);\n this._value = value;\n this._next = undefined;\n this._prev = undefined;\n }\n\n protected override _next: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the next node link.\n * @remarks Time O(1), Space O(1)\n * @returns Next node or undefined.\n */\n\n override get next(): DoublyLinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Set the next node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Next node or undefined.\n * @returns void\n */\n\n override set next(value: DoublyLinkedListNode<E> | undefined) {\n this._next = value;\n }\n\n protected _prev: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the previous node link.\n * @remarks Time O(1), Space O(1)\n * @returns Previous node or undefined.\n */\n\n get prev(): DoublyLinkedListNode<E> | undefined {\n return this._prev;\n }\n\n /**\n * Set the previous node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Previous node or undefined.\n * @returns void\n */\n\n set prev(value: DoublyLinkedListNode<E> | undefined) {\n this._prev = value;\n }\n}\n\n/**\n * Doubly linked list with O(1) push/pop/unshift/shift and linear scans.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.\n * 2. Bidirectional Traversal: Unlike singly linked lists, doubly linked lists can be easily traversed forwards or backwards. This makes insertions and deletions in the list more flexible and efficient.\n * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.\n * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.\n * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).\n * @example\n * // basic DoublyLinkedList creation and push operation\n * // Create a simple DoublyLinkedList with initial values\n * const list = new DoublyLinkedList([1, 2, 3, 4, 5]);\n *\n * // Verify the list maintains insertion order\n * console.log([...list]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(list.length); // 5;\n *\n * // Push a new element to the end\n * list.push(6);\n * console.log(list.length); // 6;\n * console.log([...list]); // [1, 2, 3, 4, 5, 6];\n * @example\n * // DoublyLinkedList pop and shift operations\n * const list = new DoublyLinkedList<number>([10, 20, 30, 40, 50]);\n *\n * // Pop removes from the end\n * const last = list.pop();\n * console.log(last); // 50;\n *\n * // Shift removes from the beginning\n * const first = list.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements\n * console.log([...list]); // [20, 30, 40];\n * console.log(list.length); // 3;\n * @example\n * // DoublyLinkedList for...of iteration and map operation\n * const list = new DoublyLinkedList<number>([1, 2, 3, 4, 5]);\n *\n * // Iterate through list\n * const doubled = list.map(value => value * 2);\n * console.log(doubled.length); // 5;\n *\n * // Use for...of loop\n * const result: number[] = [];\n * for (const item of list) {\n * result.push(item);\n * }\n * console.log(result); // [1, 2, 3, 4, 5];\n * @example\n * // Browser history\n * const browserHistory = new DoublyLinkedList<string>();\n *\n * browserHistory.push('home page');\n * browserHistory.push('search page');\n * browserHistory.push('details page');\n *\n * console.log(browserHistory.last); // 'details page';\n * console.log(browserHistory.pop()); // 'details page';\n * console.log(browserHistory.last); // 'search page';\n * @example\n * // DoublyLinkedList for LRU cache implementation\n * interface CacheEntry {\n * key: string;\n * value: string;\n * }\n *\n * // Simulate LRU cache using DoublyLinkedList\n * // DoublyLinkedList is perfect because:\n * // - O(1) delete from any position\n * // - O(1) push to end\n * // - Bidirectional traversal for LRU policy\n *\n * const cacheList = new DoublyLinkedList<CacheEntry>();\n * const maxSize = 3;\n *\n * // Add cache entries\n * cacheList.push({ key: 'user:1', value: 'Alice' });\n * cacheList.push({ key: 'user:2', value: 'Bob' });\n * cacheList.push({ key: 'user:3', value: 'Charlie' });\n *\n * // Try to add a new entry when cache is full\n * if (cacheList.length >= maxSize) {\n * // Remove the oldest (first) entry\n * const evicted = cacheList.shift();\n * console.log(evicted?.key); // 'user:1';\n * }\n *\n * // Add new entry\n * cacheList.push({ key: 'user:4', value: 'Diana' });\n *\n * // Verify current cache state\n * console.log(cacheList.length); // 3;\n * const cachedKeys = [...cacheList].map(entry => entry.key);\n * console.log(cachedKeys); // ['user:2', 'user:3', 'user:4'];\n *\n * // Access entry (in real LRU, this would move it to end)\n * const foundEntry = [...cacheList].find(entry => entry.key === 'user:2');\n * console.log(foundEntry?.value); // 'Bob';\n */\nexport class DoublyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, DoublyLinkedListNode<E>> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a DoublyLinkedList and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @param [options] - Options such as maxLen and toElementFn.\n * @returns New DoublyLinkedList instance.\n */\n\n constructor(\n elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>> = [],\n options?: DoublyLinkedListOptions<E, R>\n ) {\n super(options);\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n\n if (options?.maxLen && Number.isInteger(options.maxLen) && options.maxLen > 0) {\n this._maxLen = options.maxLen;\n }\n\n this.pushMany(elements);\n }\n\n protected _head: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the head node.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or undefined.\n */\n\n get head(): DoublyLinkedListNode<E> | undefined {\n return this._head;\n }\n\n protected _tail: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the tail node.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or undefined.\n */\n\n get tail(): DoublyLinkedListNode<E> | undefined {\n return this._tail;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this._length;\n }\n\n /**\n * Get the first element value.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n return this.head?.value;\n }\n\n /**\n * Get the last element value.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n return this.tail?.value;\n }\n\n /**\n * Create a new list from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param data - Array of elements to insert.\n * @returns A new list populated with the array's elements.\n */\n\n static fromArray<E, R = any>(\n this: new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => any,\n data: E[]\n ) {\n return new this(data);\n }\n\n /**\n * Type guard: check whether the input is a DoublyLinkedListNode.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns True if the value is a DoublyLinkedListNode.\n */\n\n isNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is DoublyLinkedListNode<E> {\n return elementNodeOrPredicate instanceof DoublyLinkedListNode;\n }\n\n /**\n * Append an element/node to the tail.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to append.\n * @returns True when appended.\n */\n\n push(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.prev = this.tail;\n this.tail!.next = newNode;\n this._tail = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the tail element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (!this.tail) return undefined;\n const removed = this.tail;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._tail = removed.prev;\n this.tail!.next = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Remove and return the head element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (!this.head) return undefined;\n const removed = this.head;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._head = removed.next;\n this.head!.prev = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Prepend an element/node to the head.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to prepend.\n * @returns True when prepended.\n */\n\n unshift(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.next = this.head;\n this.head!.prev = newNode;\n this._head = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this._length > this._maxLen) this.pop();\n return true;\n }\n\n /**\n * Append a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.unshift(this.toElementFn(el as R)));\n else ans.push(this.unshift(el as E | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Get the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current!.value;\n }\n\n /**\n * Get the node reference at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Node or undefined.\n */\n\n getNodeAt(index: number): DoublyLinkedListNode<E> | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current;\n }\n\n /**\n * Find a node by value, reference, or predicate.\n * @remarks Time O(N), Space O(1)\n * @param [elementNodeOrPredicate] - Element, node, or predicate to match.\n * @returns Matching node or undefined.\n */\n\n getNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean) | undefined\n ): DoublyLinkedListNode<E> | undefined {\n if (elementNodeOrPredicate === undefined) return;\n\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n\n let cur = this.head;\n while (cur) {\n if (cur === target) return target;\n cur = cur.next;\n }\n\n const isMatch = (node: DoublyLinkedListNode<E>) => this._equals(node.value, target.value);\n cur = this.head;\n while (cur) {\n if (isMatch(cur)) return cur;\n cur = cur.next;\n }\n return undefined;\n }\n\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Insert a new element/node at an index, shifting following nodes.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n if (index < 0 || index > this._length) return false;\n if (index === 0) return this.unshift(newElementOrNode);\n if (index === this._length) return this.push(newElementOrNode);\n\n const newNode = this._ensureNode(newElementOrNode);\n const prevNode = this.getNodeAt(index - 1)!;\n const nextNode = prevNode.next!;\n newNode.prev = prevNode;\n newNode.next = nextNode;\n prevNode.next = newNode;\n nextNode.prev = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node before an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addBefore(\n existingElementOrNode: E | DoublyLinkedListNode<E>,\n newElementOrNode: E | DoublyLinkedListNode<E>\n ): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.prev = existingNode.prev;\n if (existingNode.prev) existingNode.prev.next = newNode;\n newNode.next = existingNode;\n existingNode.prev = newNode;\n if (existingNode === this.head) this._head = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node after an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAfter(existingElementOrNode: E | DoublyLinkedListNode<E>, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.next = existingNode.next;\n if (existingNode.next) existingNode.next.prev = newNode;\n newNode.prev = existingNode;\n existingNode.next = newNode;\n if (existingNode === this.tail) this._tail = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Set the element value at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param value - New value.\n * @returns True if updated.\n */\n\n setAt(index: number, value: E): boolean {\n const node = this.getNodeAt(index);\n if (!node) return false;\n node.value = value;\n return true;\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this._length) return;\n if (index === 0) return this.shift();\n if (index === this._length - 1) return this.pop();\n\n const removedNode = this.getNodeAt(index)!;\n const prevNode = removedNode.prev!;\n const nextNode = removedNode.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n return removedNode.value;\n }\n\n /**\n * Delete the first match by value/node.\n * @remarks Time O(N), Space O(1)\n * @param [elementOrNode] - Element or node to remove.\n * @returns True if removed.\n */\n\n delete(elementOrNode: E | DoublyLinkedListNode<E> | undefined): boolean {\n const node = this.getNode(elementOrNode);\n if (!node) return false;\n\n if (node === this.head) this.shift();\n else if (node === this.tail) this.pop();\n else {\n const prevNode = node.prev!;\n const nextNode = node.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n }\n return true;\n }\n\n /**\n * Check whether the list is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this._length === 0;\n }\n\n /**\n * Remove all nodes and reset length.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n }\n\n /**\n * Find the first value matching a predicate scanning forward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n search(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Find the first value matching a predicate scanning backward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n getBackward(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.tail;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.prev;\n }\n return undefined;\n }\n\n /**\n * Reverse the list in place.\n * @remarks Time O(N), Space O(1)\n * @returns This list.\n */\n\n reverse(): this {\n let current = this.head;\n [this._head, this._tail] = [this.tail, this.head];\n while (current) {\n const next = current.next;\n [current.prev, current.next] = [current.next, current.prev];\n current = next;\n }\n return this;\n }\n\n /**\n * Set the equality comparator used to compare values.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This list.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Deep clone this list (values are copied by reference).\n * @remarks Time O(N), Space O(N)\n * @returns A new list with the same element sequence.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Predicate (value, index, list) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with kept values.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) if (callback.call(thisArg, v, index++, this)) out.push(v);\n return out;\n }\n\n /**\n * Map values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, list) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new list (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, list) → newElement.\n * @param [options] - Options for the output list (e.g., maxLen, toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new DoublyLinkedList with mapped values.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: DoublyLinkedListOptions<EM, RM>,\n thisArg?: any\n ): DoublyLinkedList<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}), maxLen: this._maxLen });\n let index = 0;\n for (const v of this) out.push(callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * (Protected) Create or return a node for the given input (node or raw element).\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element value or node to normalize.\n * @returns A DoublyLinkedListNode for the provided input.\n */\n\n protected _ensureNode(elementOrNode: E | DoublyLinkedListNode<E>) {\n if (this.isNode(elementOrNode)) return elementOrNode;\n return new DoublyLinkedListNode<E>(elementOrNode);\n }\n\n /**\n * (Protected) Normalize input into a predicate over nodes.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate.\n * @returns A predicate function taking a node and returning true/false.\n */\n\n protected _ensurePredicate(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): (node: DoublyLinkedListNode<E>) => boolean {\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n return (node: DoublyLinkedListNode<E>) => node === target;\n }\n if (typeof elementNodeOrPredicate === 'function') {\n return elementNodeOrPredicate as (node: DoublyLinkedListNode<E>) => boolean;\n }\n const value = elementNodeOrPredicate as E;\n return (node: DoublyLinkedListNode<E>) => this._equals(node.value, value);\n }\n\n /**\n * (Protected) Get the previous node of a given node.\n * @remarks Time O(1), Space O(1)\n * @param node - A node in the list.\n * @returns Previous node or undefined.\n */\n\n protected _getPrevNode(node: DoublyLinkedListNode<E>): DoublyLinkedListNode<E> | undefined {\n return node.prev;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind list instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => this;\n return new Ctor([], options as DoublyLinkedListOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new list.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind DoublyLinkedList instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>> = [],\n options?: DoublyLinkedListOptions<EM, RM>\n ): DoublyLinkedList<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>>,\n options?: DoublyLinkedListOptions<EM, RM>\n ) => DoublyLinkedList<EM, RM>;\n return new Ctor(elements, options);\n }\n\n protected *_getIterator(): IterableIterator<E> {\n let current = this.head;\n while (current) {\n yield current.value;\n current = current.next;\n }\n }\n\n protected *_getReverseIterator(): IterableIterator<E> {\n let current = this.tail;\n while (current) {\n yield current.value;\n current = current.prev;\n }\n }\n\n protected *_getNodeIterator(): IterableIterator<DoublyLinkedListNode<E>> {\n let current = this.head;\n while (current) {\n yield current;\n current = current.next;\n }\n }\n}\n","import type { SkipLinkedListOptions } from '../../types';\n\nexport class SkipListNode<K, V> {\n key: K;\n value: V;\n forward: SkipListNode<K, V>[];\n\n constructor(key: K, value: V, level: number) {\n this.key = key;\n this.value = value;\n this.forward = new Array(level);\n }\n}\n\nexport class SkipList<K, V> {\n constructor(elements: Iterable<[K, V]> = [], options?: SkipLinkedListOptions) {\n if (options) {\n const { maxLevel, probability } = options;\n if (typeof maxLevel === 'number') this._maxLevel = maxLevel;\n if (typeof probability === 'number') this._probability = probability;\n }\n\n if (elements) {\n for (const [key, value] of elements) this.add(key, value);\n }\n }\n\n protected _head: SkipListNode<K, V> = new SkipListNode<K, V>(undefined as K, undefined as V, this.maxLevel);\n\n get head(): SkipListNode<K, V> {\n return this._head;\n }\n\n protected _level: number = 0;\n\n get level(): number {\n return this._level;\n }\n\n protected _maxLevel: number = 16;\n\n get maxLevel(): number {\n return this._maxLevel;\n }\n\n protected _probability: number = 0.5;\n\n get probability(): number {\n return this._probability;\n }\n\n get first(): V | undefined {\n const firstNode = this.head.forward[0];\n return firstNode ? firstNode.value : undefined;\n }\n\n get last(): V | undefined {\n let current = this.head;\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i]) {\n current = current.forward[i];\n }\n }\n return current.value;\n }\n\n add(key: K, value: V): void {\n const newNode = new SkipListNode(key, value, this._randomLevel());\n const update: SkipListNode<K, V>[] = new Array(this.maxLevel).fill(this.head);\n let current = this.head;\n\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n update[i] = current;\n }\n\n for (let i = 0; i < newNode.forward.length; i++) {\n newNode.forward[i] = update[i].forward[i];\n update[i].forward[i] = newNode;\n }\n\n if (!newNode.forward[0]) {\n this._level = Math.max(this.level, newNode.forward.length);\n }\n }\n\n get(key: K): V | undefined {\n let current = this.head;\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n }\n\n current = current.forward[0];\n\n if (current && current.key === key) {\n return current.value;\n }\n\n return undefined;\n }\n\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n delete(key: K): boolean {\n const update: SkipListNode<K, V>[] = new Array(this.maxLevel).fill(this.head);\n let current = this.head;\n\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n update[i] = current;\n }\n\n current = current.forward[0];\n\n if (current && current.key === key) {\n for (let i = 0; i < this.level; i++) {\n if (update[i].forward[i] !== current) {\n break;\n }\n update[i].forward[i] = current.forward[i];\n }\n while (this.level > 0 && !this.head.forward[this.level - 1]) {\n this._level--;\n }\n return true;\n }\n\n return false;\n }\n\n higher(key: K): V | undefined {\n let current = this.head;\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key <= key) {\n current = current.forward[i];\n }\n }\n const nextNode = current.forward[0];\n return nextNode ? nextNode.value : undefined;\n }\n\n lower(key: K): V | undefined {\n let current = this.head;\n let lastLess = undefined;\n\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n if (current.key < key) {\n lastLess = current;\n }\n }\n\n return lastLess ? lastLess.value : undefined;\n }\n\n protected _randomLevel(): number {\n let level = 1;\n while (Math.random() < this.probability && level < this.maxLevel) {\n level++;\n }\n return level;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, IterableElementBaseOptions, StackOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * LIFO stack with array storage and optional record→element conversion.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Last In, First Out (LIFO): The core characteristic of a stack is its last in, first out nature, meaning the last element added to the stack will be the first to be removed.\n * 2. Uses: Stacks are commonly used for managing a series of tasks or elements that need to be processed in a last in, first out manner. They are widely used in various scenarios, such as in function calls in programming languages, evaluation of arithmetic expressions, and backtracking algorithms.\n * 3. Performance: Stack operations are typically O(1) in time complexity, meaning that regardless of the stack's size, adding, removing, and viewing the top element are very fast operations.\n * 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.\n * 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.\n * 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.\n * @example\n * // basic Stack creation and push operation\n * // Create a simple Stack with initial values\n * const stack = new Stack([1, 2, 3, 4, 5]);\n *\n * // Verify the stack maintains insertion order (LIFO will be shown in pop)\n * console.log([...stack]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(stack.size); // 5;\n *\n * // Push a new element to the top\n * stack.push(6);\n * console.log(stack.size); // 6;\n * @example\n * // Stack pop operation (LIFO - Last In First Out)\n * const stack = new Stack<number>([10, 20, 30, 40, 50]);\n *\n * // Peek at the top element without removing\n * const top = stack.peek();\n * console.log(top); // 50;\n *\n * // Pop removes from the top (LIFO order)\n * const popped = stack.pop();\n * console.log(popped); // 50;\n *\n * // Next pop gets the previous element\n * const next = stack.pop();\n * console.log(next); // 40;\n *\n * // Verify length decreased\n * console.log(stack.size); // 3;\n * @example\n * // Function Call Stack\n * const functionStack = new Stack<string>();\n * functionStack.push('main');\n * functionStack.push('foo');\n * functionStack.push('bar');\n * console.log(functionStack.pop()); // 'bar';\n * console.log(functionStack.pop()); // 'foo';\n * console.log(functionStack.pop()); // 'main';\n * @example\n * // Balanced Parentheses or Brackets\n * type ValidCharacters = ')' | '(' | ']' | '[' | '}' | '{';\n *\n * const stack = new Stack<string>();\n * const input: ValidCharacters[] = '[({})]'.split('') as ValidCharacters[];\n * const matches: { [key in ValidCharacters]?: ValidCharacters } = { ')': '(', ']': '[', '}': '{' };\n * for (const char of input) {\n * if ('([{'.includes(char)) {\n * stack.push(char);\n * } else if (')]}'.includes(char)) {\n * if (stack.pop() !== matches[char]) {\n * fail('Parentheses are not balanced');\n * }\n * }\n * }\n * console.log(stack.isEmpty()); // true;\n * @example\n * // Expression Evaluation and Conversion\n * const stack = new Stack<number>();\n * const expression = [5, 3, '+']; // Equivalent to 5 + 3\n * expression.forEach(token => {\n * if (typeof token === 'number') {\n * stack.push(token);\n * } else {\n * const b = stack.pop()!;\n * const a = stack.pop()!;\n * stack.push(token === '+' ? a + b : 0); // Only handling '+' here\n * }\n * });\n * console.log(stack.pop()); // 8;\n * @example\n * // Backtracking Algorithms\n * const stack = new Stack<[number, number]>();\n * const maze = [\n * ['S', ' ', 'X'],\n * ['X', ' ', 'X'],\n * [' ', ' ', 'E']\n * ];\n * const start: [number, number] = [0, 0];\n * const end = [2, 2];\n * const directions = [\n * [0, 1], // To the right\n * [1, 0], // down\n * [0, -1], // left\n * [-1, 0] // up\n * ];\n *\n * const visited = new Set<string>(); // Used to record visited nodes\n * stack.push(start);\n * const path: number[][] = [];\n *\n * while (!stack.isEmpty()) {\n * const [x, y] = stack.pop()!;\n * if (visited.has(`${x},${y}`)) continue; // Skip already visited nodes\n * visited.add(`${x},${y}`);\n *\n * path.push([x, y]);\n *\n * if (x === end[0] && y === end[1]) {\n * break; // Find the end point and exit\n * }\n *\n * for (const [dx, dy] of directions) {\n * const nx = x + dx;\n * const ny = y + dy;\n * if (\n * maze[nx]?.[ny] === ' ' || // feasible path\n * maze[nx]?.[ny] === 'E' // destination\n * ) {\n * stack.push([nx, ny]);\n * }\n * }\n * }\n *\n * console.log(path); // contains end;\n * @example\n * // Stock Span Problem\n * const stack = new Stack<number>();\n * const prices = [100, 80, 60, 70, 60, 75, 85];\n * const spans: number[] = [];\n * prices.forEach((price, i) => {\n * while (!stack.isEmpty() && prices[stack.peek()!] <= price) {\n * stack.pop();\n * }\n * spans.push(stack.isEmpty() ? i + 1 : i - stack.peek()!);\n * stack.push(i);\n * });\n * console.log(spans); // [1, 1, 1, 2, 1, 4, 6];\n * @example\n * // Simplify File Paths\n * const stack = new Stack<string>();\n * const path = '/a/./b/../../c';\n * path.split('/').forEach(segment => {\n * if (segment === '..') stack.pop();\n * else if (segment && segment !== '.') stack.push(segment);\n * });\n * console.log(stack.elements.join('/')); // 'c';\n */\nexport class Stack<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a Stack and optionally bulk-push elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn and equality function.\n * @returns New Stack instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: StackOptions<E, R>) {\n super(options);\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of stored elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Create a stack from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param elements - Array of elements to push in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Stack populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => any,\n elements: E[],\n options?: StackOptions<E, R>\n ) {\n return new this(elements, options);\n }\n\n /**\n * Check whether the stack is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.elements.length === 0;\n }\n\n /**\n * Get the top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.isEmpty() ? undefined : this.elements[this.elements.length - 1];\n }\n\n /**\n * Push one element onto the top.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to push.\n * @returns True when pushed.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n return true;\n }\n\n /**\n * Pop and return the top element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n return this.isEmpty() ? undefined : this.elements.pop();\n }\n\n /**\n * Push many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx);\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the bottom.\n * @returns True if removed.\n */\n\n deleteAt(index: number): boolean {\n if (index < 0 || index >= this.elements.length) return false;\n const spliced = this.elements.splice(index, 1);\n return spliced.length === 1;\n }\n\n /**\n * Delete the first element that satisfies a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, stack) → boolean to decide deletion.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, stack: this) => boolean): boolean {\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Remove all elements and reset storage.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Deep clone this stack.\n * @remarks Time O(N), Space O(N)\n * @returns A new stack with the same content.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter elements into a new stack of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, stack) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new stack with kept values.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map values into a new stack of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, stack) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new stack with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new stack (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, stack) → newElement.\n * @param [options] - Options for the output stack (e.g., toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Stack with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): Stack<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}) });\n let index = 0;\n for (const v of this) {\n out.push(thisArg === undefined ? callback(v, index, this) : callback.call(thisArg, v, index, this));\n index++;\n }\n return out;\n }\n\n /**\n * Set the equality comparator used by delete/search operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This stack.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * (Protected) Find the index of a target element using the equality function.\n * @remarks Time O(N), Space O(1)\n * @param target - Element to search for.\n * @returns Index or -1 if not found.\n */\n\n protected _indexOfByEquals(target: E): number {\n for (let i = 0; i < this.elements.length; i++) if (this._equals(this.elements[i], target)) return i;\n return -1;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind stack instance.\n */\n\n protected _createInstance(options?: StackOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => this;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind stack and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new stack.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Stack instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: Iterable<T> | Iterable<RR> = [],\n options?: StackOptions<T, RR>\n ): Stack<T, RR> {\n const Ctor = this.constructor as new (\n elements?: Iterable<T> | Iterable<RR>,\n options?: StackOptions<T, RR>\n ) => Stack<T, RR>;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from bottom to top.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this.elements.length; i++) yield this.elements[i];\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, LinearBaseOptions, QueueOptions } from '../../types';\nimport { SinglyLinkedList } from '../linked-list';\nimport { LinearBase } from '../base/linear-base';\n\n/**\n * Array-backed queue with amortized O(1) enqueue/dequeue via an offset pointer and optional auto-compaction.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. First In, First Out (FIFO): The core feature of a queue is its first in, first out nature. The element added to the queue first will be the one to be removed first.\n * 2. Operations: The main operations include enqueue (adding an element to the end of the queue) and dequeue (removing and returning the element at the front of the queue). Typically, there is also a peek operation (looking at the front element without removing it).\n * 3. Uses: Queues are commonly used to manage a series of tasks or elements that need to be processed in order. For example, managing task queues in a multi-threaded environment, or in algorithms for data structures like trees and graphs for breadth-first search.\n * 4. Task Scheduling: Managing the order of task execution in operating systems or applications.\n * 5. Data Buffering: Acting as a buffer for data packets in network communication.\n * 6. Breadth-First Search (BFS): In traversal algorithms for graphs and trees, queues store elements that are to be visited.\n * 7. Real-time Queuing: Like queuing systems in banks or supermarkets.\n * @example\n * // basic Queue creation and push operation\n * // Create a simple Queue with initial values\n * const queue = new Queue([1, 2, 3, 4, 5]);\n *\n * // Verify the queue maintains insertion order\n * console.log([...queue]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(queue.length); // 5;\n * @example\n * // Queue shift and peek operations\n * const queue = new Queue<number>([10, 20, 30, 40]);\n *\n * // Peek at the front element without removing it\n * console.log(queue.first); // 10;\n *\n * // Remove and get the first element (FIFO)\n * const first = queue.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements and length decreased\n * console.log([...queue]); // [20, 30, 40];\n * console.log(queue.length); // 3;\n * @example\n * // Queue for...of iteration and isEmpty check\n * const queue = new Queue<string>(['A', 'B', 'C', 'D']);\n *\n * const elements: string[] = [];\n * for (const item of queue) {\n * elements.push(item);\n * }\n *\n * // Verify all elements are iterated in order\n * console.log(elements); // ['A', 'B', 'C', 'D'];\n *\n * // Process all elements\n * while (queue.length > 0) {\n * queue.shift();\n * }\n *\n * console.log(queue.length); // 0;\n * @example\n * // Queue as message broker for event processing\n * interface Message {\n * id: string;\n * type: 'email' | 'sms' | 'push';\n * recipient: string;\n * content: string;\n * timestamp: Date;\n * }\n *\n * // Create a message queue for real-time event processing\n * const messageQueue = new Queue<Message>([\n * {\n * id: 'msg-001',\n * type: 'email',\n * recipient: 'user@example.com',\n * content: 'Welcome!',\n * timestamp: new Date()\n * },\n * {\n * id: 'msg-002',\n * type: 'sms',\n * recipient: '+1234567890',\n * content: 'OTP: 123456',\n * timestamp: new Date()\n * },\n * {\n * id: 'msg-003',\n * type: 'push',\n * recipient: 'device-token-xyz',\n * content: 'New notification',\n * timestamp: new Date()\n * },\n * {\n * id: 'msg-004',\n * type: 'email',\n * recipient: 'admin@example.com',\n * content: 'Daily report',\n * timestamp: new Date()\n * }\n * ]);\n *\n * // Process messages in FIFO order (first message first)\n * const processedMessages: string[] = [];\n * while (messageQueue.length > 0) {\n * const message = messageQueue.shift();\n * if (message) {\n * processedMessages.push(`${message.type}:${message.recipient}`);\n * }\n * }\n *\n * // Verify messages were processed in order\n * console.log(processedMessages); // [\n * // 'email:user@example.com',\n * // 'sms:+1234567890',\n * // 'push:device-token-xyz',\n * // 'email:admin@example.com'\n * // ];\n *\n * // Queue should be empty after processing all messages\n * console.log(messageQueue.length); // 0;\n */\nexport class Queue<E = any, R = any> extends LinearBase<E, R> {\n /**\n * Create a Queue and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn, maxLen, and autoCompactRatio.\n * @returns New Queue instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: QueueOptions<E, R>) {\n super(options);\n if (options) {\n const { autoCompactRatio = 0.5 } = options;\n this._autoCompactRatio = autoCompactRatio;\n }\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the underlying array buffer.\n * @remarks Time O(1), Space O(1)\n * @returns Backing array of elements.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n protected _offset = 0;\n\n /**\n * Get the current start offset into the array.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based offset.\n */\n\n get offset(): number {\n return this._offset;\n }\n\n protected _autoCompactRatio = 0.5;\n\n /**\n * Get the compaction threshold (offset/size).\n * @remarks Time O(1), Space O(1)\n * @returns Auto-compaction ratio in (0,1].\n */\n\n get autoCompactRatio(): number {\n return this._autoCompactRatio;\n }\n\n /**\n * Set the compaction threshold.\n * @remarks Time O(1), Space O(1)\n * @param value - New ratio; compacts when offset/size exceeds this value.\n * @returns void\n */\n\n set autoCompactRatio(value: number) {\n this._autoCompactRatio = value;\n }\n\n /**\n * Get the number of elements currently in the queue.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this.elements.length - this._offset;\n }\n\n /**\n * Get the first element (front) without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Front element or undefined.\n */\n\n get first(): E | undefined {\n return this.length > 0 ? this.elements[this._offset] : undefined;\n }\n\n /**\n * Get the last element (back) without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Back element or undefined.\n */\n\n get last(): E | undefined {\n return this.length > 0 ? this.elements[this.elements.length - 1] : undefined;\n }\n\n /**\n * Create a queue from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @param elements - Array of elements to enqueue in order.\n * @returns A new queue populated from the array.\n */\n\n static fromArray<E>(elements: E[]): Queue<E> {\n return new Queue(elements);\n }\n\n /**\n * Check whether the queue is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n /**\n * Enqueue one element at the back.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to enqueue.\n * @returns True on success.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Enqueue many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Dequeue one element from the front (amortized via offset).\n * @remarks Time O(1) amortized, Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (this.length === 0) return undefined;\n const first = this.first;\n this._offset += 1;\n if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();\n return first;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (strict equality via Object.is).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n for (let i = this._offset; i < this.elements.length; i++) {\n if (Object.is(this.elements[i], element)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the element at a given logical index.\n * @remarks Time O(1), Space O(1)\n * @param index - Zero-based index from the front.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this.length) return undefined;\n return this._elements[this._offset + index];\n }\n\n /**\n * Delete the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the front.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this.length) return undefined;\n const gi = this._offset + index;\n const [deleted] = this.elements.splice(gi, 1);\n return deleted;\n }\n\n /**\n * Insert a new element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the front.\n * @param newElement - Element to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElement: E): boolean {\n if (index < 0 || index > this.length) return false;\n this._elements.splice(this._offset + index, 0, newElement);\n return true;\n }\n\n /**\n * Replace the element at a given index.\n * @remarks Time O(1), Space O(1)\n * @param index - Zero-based index from the front.\n * @param newElement - New element to set.\n * @returns True if updated.\n */\n\n setAt(index: number, newElement: E): boolean {\n if (index < 0 || index >= this.length) return false;\n this._elements[this._offset + index] = newElement;\n return true;\n }\n\n /**\n * Reverse the queue in-place by compacting then reversing.\n * @remarks Time O(N), Space O(N)\n * @returns This queue.\n */\n\n reverse(): this {\n this._elements = this.elements.slice(this._offset).reverse();\n this._offset = 0;\n return this;\n }\n\n /**\n * Remove all elements and reset offset.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n this._offset = 0;\n }\n\n /**\n * Compact storage by discarding consumed head elements.\n * @remarks Time O(N), Space O(N)\n * @returns True when compaction performed.\n */\n\n compact(): boolean {\n this._elements = this.elements.slice(this._offset);\n this._offset = 0;\n return true;\n }\n\n /**\n * Remove and/or insert elements at a position (array-like).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default 0).\n * @param [items] - Elements to insert after `start`.\n * @returns A new queue containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));\n\n const gi = this._offset + start;\n const removedArray = this._elements.splice(gi, deleteCount, ...items);\n\n if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();\n\n const removed = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n removed._setAutoCompactRatio(this._autoCompactRatio);\n removed.pushMany(removedArray);\n\n return removed as unknown as this;\n }\n\n /**\n * Deep clone this queue and its parameters.\n * @remarks Time O(N), Space O(N)\n * @returns A new queue with the same content and options.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setAutoCompactRatio(this._autoCompactRatio);\n for (let i = this._offset; i < this.elements.length; i++) out.push(this.elements[i]);\n return out;\n }\n\n /**\n * Filter elements into a new queue of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (element, index, queue) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new queue with kept elements.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setAutoCompactRatio(this._autoCompactRatio);\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map each element to a new element in a possibly different-typed queue.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, queue) → newElement.\n * @param [options] - Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Queue with mapped elements.\n */\n\n map<EM, RM>(callback: ElementCallback<E, R, EM>, options?: QueueOptions<EM, RM>, thisArg?: unknown): Queue<EM, RM> {\n const out = new (this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: QueueOptions<EM, RM>\n ) => Queue<EM, RM>)([], {\n toElementFn: options?.toElementFn,\n maxLen: options?.maxLen ?? this._maxLen,\n autoCompactRatio: options?.autoCompactRatio ?? this._autoCompactRatio\n });\n let index = 0;\n for (const v of this)\n out.push(thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * Map each element to a new value of the same type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (element, index, queue) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new queue with mapped elements (same element type).\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R>,\n options?: QueueOptions<E, R>\n ) => Queue<E, R>;\n const out = new Ctor([], {\n toElementFn: this.toElementFn,\n maxLen: this._maxLen,\n autoCompactRatio: this._autoCompactRatio\n });\n out._setAutoCompactRatio?.(this._autoCompactRatio);\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out as this;\n }\n\n /**\n * (Protected) Set the internal auto-compaction ratio.\n * @remarks Time O(1), Space O(1)\n * @param value - New ratio to assign.\n * @returns void\n */\n\n protected _setAutoCompactRatio(value: number): void {\n this._autoCompactRatio = value;\n }\n\n /**\n * (Protected) Iterate elements from front to back.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of E.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = this._offset; i < this.elements.length; i++) yield this.elements[i];\n }\n\n /**\n * (Protected) Iterate elements from back to front.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of E.\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n for (let i = this.length - 1; i >= 0; i--) {\n const cur = this.at(i);\n if (cur !== undefined) yield cur;\n }\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind queue instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: QueueOptions<E, R>) => this;\n return new Ctor([], options as QueueOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind queue and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new queue.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Queue instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: QueueOptions<EM, RM>\n ): Queue<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: QueueOptions<EM, RM>\n ) => Queue<EM, RM>;\n return new Ctor(elements, options);\n }\n}\n\n/**\n * Queue implemented over a singly linked list; preserves head/tail operations with linear scans for queries.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * @example examples will be generated by unit test\n */\nexport class LinkedListQueue<E = any, R = any> extends SinglyLinkedList<E, R> {\n /**\n * Deep clone this linked-list-based queue.\n * @remarks Time O(N), Space O(N)\n * @returns A new queue with the same sequence of elements.\n */\n\n override clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n for (const v of this) out.push(v);\n return out;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n DequeOptions,\n ElementCallback,\n IterableElementBaseOptions,\n IterableWithSizeOrLength,\n LinearBaseOptions\n} from '../../types';\nimport { calcMinUnitsRequired, rangeCheck } from '../../utils';\nimport { LinearBase } from '../base/linear-base';\n\n/**\n * Deque implemented with circular buckets allowing O(1) amortized push/pop at both ends.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).\n * 2. Efficient Random Access: Being based on an array, it offers fast random access capability, allowing constant time access to any element.\n * 3. Continuous Memory Allocation: Since it is based on an array, all elements are stored contiguously in memory, which can bring cache friendliness and efficient memory access.\n * 4. Efficiency: Adding and removing elements at both ends of a deque is usually very fast. However, when the dynamic array needs to expand, it may involve copying the entire array to a larger one, and this operation has a time complexity of O(n).\n * 5. Performance jitter: Deque may experience performance jitter, but DoublyLinkedList will not\n * @example\n * // basic Deque creation and push/pop operations\n * // Create a simple Deque with initial values\n * const deque = new Deque([1, 2, 3, 4, 5]);\n *\n * // Verify the deque maintains insertion order\n * console.log([...deque]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(deque.length); // 5;\n *\n * // Push to the end\n * deque.push(6);\n * console.log(deque.length); // 6;\n *\n * // Pop from the end\n * const last = deque.pop();\n * console.log(last); // 6;\n * @example\n * // Deque shift and unshift operations\n * const deque = new Deque<number>([20, 30, 40]);\n *\n * // Unshift adds to the front\n * deque.unshift(10);\n * console.log([...deque]); // [10, 20, 30, 40];\n *\n * // Shift removes from the front (O(1) complexity!)\n * const first = deque.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements\n * console.log([...deque]); // [20, 30, 40];\n * console.log(deque.length); // 3;\n * @example\n * // Deque peek at both ends\n * const deque = new Deque<number>([10, 20, 30, 40, 50]);\n *\n * // Get first element without removing\n * const first = deque.at(0);\n * console.log(first); // 10;\n *\n * // Get last element without removing\n * const last = deque.at(deque.length - 1);\n * console.log(last); // 50;\n *\n * // Length unchanged\n * console.log(deque.length); // 5;\n * @example\n * // Deque for...of iteration and reverse\n * const deque = new Deque<string>(['A', 'B', 'C', 'D']);\n *\n * // Iterate forward\n * const forward: string[] = [];\n * for (const item of deque) {\n * forward.push(item);\n * }\n * console.log(forward); // ['A', 'B', 'C', 'D'];\n *\n * // Reverse the deque\n * deque.reverse();\n * const backward: string[] = [];\n * for (const item of deque) {\n * backward.push(item);\n * }\n * console.log(backward); // ['D', 'C', 'B', 'A'];\n * @example\n * // Deque as sliding window for stream processing\n * interface DataPoint {\n * timestamp: number;\n * value: number;\n * sensor: string;\n * }\n *\n * // Create a deque-based sliding window for real-time data aggregation\n * const windowSize = 3;\n * const dataWindow = new Deque<DataPoint>();\n *\n * // Simulate incoming sensor data stream\n * const incomingData: DataPoint[] = [\n * { timestamp: 1000, value: 25.5, sensor: 'temp-01' },\n * { timestamp: 1100, value: 26.2, sensor: 'temp-01' },\n * { timestamp: 1200, value: 25.8, sensor: 'temp-01' },\n * { timestamp: 1300, value: 27.1, sensor: 'temp-01' },\n * { timestamp: 1400, value: 26.9, sensor: 'temp-01' }\n * ];\n *\n * const windowResults: Array<{ avgValue: number; windowSize: number }> = [];\n *\n * for (const dataPoint of incomingData) {\n * // Add new data to the end\n * dataWindow.push(dataPoint);\n *\n * // Remove oldest data when window exceeds size (O(1) from front)\n * if (dataWindow.length > windowSize) {\n * dataWindow.shift();\n * }\n *\n * // Calculate average of current window\n * let sum = 0;\n * for (const point of dataWindow) {\n * sum += point.value;\n * }\n * const avg = sum / dataWindow.length;\n *\n * windowResults.push({\n * avgValue: Math.round(avg * 10) / 10,\n * windowSize: dataWindow.length\n * });\n * }\n *\n * // Verify sliding window behavior\n * console.log(windowResults.length); // 5;\n * console.log(windowResults[0].windowSize); // 1; // First window has 1 element\n * console.log(windowResults[2].windowSize); // 3; // Windows are at max size from 3rd onwards\n * console.log(windowResults[4].windowSize); // 3; // Last window still has 3 elements\n * console.log(dataWindow.length); // 3;\n */\nexport class Deque<E = any, R = any> extends LinearBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a Deque and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable (or iterable-like) of elements/records to insert.\n * @param [options] - Options such as bucketSize, toElementFn, and maxLen.\n * @returns New Deque instance.\n */\n\n constructor(elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = [], options?: DequeOptions<E, R>) {\n super(options);\n\n if (options) {\n const { bucketSize } = options;\n if (typeof bucketSize === 'number') this._bucketSize = bucketSize;\n }\n\n let _size: number;\n if ('length' in elements) {\n _size = typeof elements.length === 'function' ? elements.length() : elements.length;\n } else {\n _size = typeof elements.size === 'function' ? elements.size() : elements.size;\n }\n\n this._bucketCount = calcMinUnitsRequired(_size, this._bucketSize) || 1;\n for (let i = 0; i < this._bucketCount; ++i) {\n this._buckets.push(new Array(this._bucketSize));\n }\n const needBucketNum = calcMinUnitsRequired(_size, this._bucketSize);\n this._bucketFirst = this._bucketLast = (this._bucketCount >> 1) - (needBucketNum >> 1);\n this._firstInBucket = this._lastInBucket = (this._bucketSize - (_size % this._bucketSize)) >> 1;\n this.pushMany(elements);\n }\n\n protected _bucketSize: number = 1 << 12;\n\n /**\n * Get the current bucket size.\n * @remarks Time O(1), Space O(1)\n * @returns Bucket capacity per bucket.\n */\n\n get bucketSize() {\n return this._bucketSize;\n }\n\n protected _bucketFirst = 0;\n\n /**\n * Get the index of the first bucket in use.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based bucket index.\n */\n\n get bucketFirst(): number {\n return this._bucketFirst;\n }\n\n protected _firstInBucket = 0;\n\n /**\n * Get the index inside the first bucket.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based index within the first bucket.\n */\n\n get firstInBucket(): number {\n return this._firstInBucket;\n }\n\n protected _bucketLast = 0;\n\n /**\n * Get the index of the last bucket in use.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based bucket index.\n */\n\n get bucketLast(): number {\n return this._bucketLast;\n }\n\n protected _lastInBucket = 0;\n\n /**\n * Get the index inside the last bucket.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based index within the last bucket.\n */\n\n get lastInBucket(): number {\n return this._lastInBucket;\n }\n\n protected _bucketCount = 0;\n\n /**\n * Get the number of buckets allocated.\n * @remarks Time O(1), Space O(1)\n * @returns Bucket count.\n */\n\n get bucketCount(): number {\n return this._bucketCount;\n }\n\n protected _buckets: E[][] = [];\n\n /**\n * Get the internal buckets array.\n * @remarks Time O(1), Space O(1)\n * @returns Array of buckets storing values.\n */\n\n get buckets() {\n return this._buckets;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements in the deque.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length() {\n return this._length;\n }\n\n /**\n * Get the first element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n if (this._length === 0) return;\n return this._buckets[this._bucketFirst][this._firstInBucket];\n }\n\n /**\n * Get the last element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n if (this._length === 0) return;\n return this._buckets[this._bucketLast][this._lastInBucket];\n }\n\n /**\n * Create a Deque from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - Constructor (subclass) to instantiate.\n * @param data - Array of elements to insert in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Deque populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (\n elements?: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>,\n options?: DequeOptions<E, R>\n ) => any,\n data: E[],\n options?: DequeOptions<E, R>\n ) {\n return new this(data, options);\n }\n\n /**\n * Append one element at the back.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to append.\n * @returns True when appended.\n */\n\n push(element: E): boolean {\n if (this._length) {\n if (this._lastInBucket < this._bucketSize - 1) {\n this._lastInBucket += 1;\n } else if (this._bucketLast < this._bucketCount - 1) {\n this._bucketLast += 1;\n this._lastInBucket = 0;\n } else {\n this._bucketLast = 0;\n this._lastInBucket = 0;\n }\n if (this._bucketLast === this._bucketFirst && this._lastInBucket === this._firstInBucket) this._reallocate();\n }\n this._length += 1;\n this._buckets[this._bucketLast][this._lastInBucket] = element;\n if (this._maxLen > 0 && this._length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the last element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (this._length === 0) return;\n const element = this._buckets[this._bucketLast][this._lastInBucket];\n if (this._length !== 1) {\n if (this._lastInBucket > 0) {\n this._lastInBucket -= 1;\n } else if (this._bucketLast > 0) {\n this._bucketLast -= 1;\n this._lastInBucket = this._bucketSize - 1;\n } else {\n this._bucketLast = this._bucketCount - 1;\n this._lastInBucket = this._bucketSize - 1;\n }\n }\n this._length -= 1;\n return element;\n }\n\n /**\n * Remove and return the first element.\n * @remarks Time O(1) amortized, Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (this._length === 0) return;\n const element = this._buckets[this._bucketFirst][this._firstInBucket];\n if (this._length !== 1) {\n if (this._firstInBucket < this._bucketSize - 1) {\n this._firstInBucket += 1;\n } else if (this._bucketFirst < this._bucketCount - 1) {\n this._bucketFirst += 1;\n this._firstInBucket = 0;\n } else {\n this._bucketFirst = 0;\n this._firstInBucket = 0;\n }\n }\n this._length -= 1;\n return element;\n }\n\n /**\n * Prepend one element at the front.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to prepend.\n * @returns True when prepended.\n */\n\n unshift(element: E): boolean {\n if (this._length) {\n if (this._firstInBucket > 0) {\n this._firstInBucket -= 1;\n } else if (this._bucketFirst > 0) {\n this._bucketFirst -= 1;\n this._firstInBucket = this._bucketSize - 1;\n } else {\n this._bucketFirst = this._bucketCount - 1;\n this._firstInBucket = this._bucketSize - 1;\n }\n if (this._bucketFirst === this._bucketLast && this._firstInBucket === this._lastInBucket) this._reallocate();\n }\n this._length += 1;\n this._buckets[this._bucketFirst][this._firstInBucket] = element;\n if (this._maxLen > 0 && this._length > this._maxLen) this.pop();\n return true;\n }\n\n /**\n * Append a sequence of elements.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable (or iterable-like) of elements/records.\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>) {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n ans.push(this.push(this.toElementFn(el as R)));\n } else {\n ans.push(this.push(el as E));\n }\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements.\n * @remarks Time O(N), Space O(1)\n * @param [elements] - Iterable (or iterable-like) of elements/records.\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = []) {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n ans.push(this.unshift(this.toElementFn(el as R)));\n } else {\n ans.push(this.unshift(el as E));\n }\n }\n return ans;\n }\n\n /**\n * Check whether the deque is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this._length === 0;\n }\n\n /**\n * Remove all elements and reset structure.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._buckets = [new Array(this._bucketSize)];\n this._bucketCount = 1;\n this._bucketFirst = this._bucketLast = this._length = 0;\n this._firstInBucket = this._lastInBucket = this._bucketSize >> 1;\n }\n\n /**\n * Get the element at a given position.\n * @remarks Time O(1), Space O(1)\n * @param pos - Zero-based position from the front.\n * @returns Element or undefined.\n */\n\n at(pos: number): E | undefined {\n if (pos < 0 || pos >= this._length) return undefined;\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n return this._buckets[bucketIndex][indexInBucket];\n }\n\n /**\n * Replace the element at a given position.\n * @remarks Time O(1), Space O(1)\n * @param pos - Zero-based position from the front.\n * @param element - New element value.\n * @returns True if updated.\n */\n\n setAt(pos: number, element: E): boolean {\n rangeCheck(pos, 0, this._length - 1);\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n this._buckets[bucketIndex][indexInBucket] = element;\n return true;\n }\n\n /**\n * Insert repeated copies of an element at a position.\n * @remarks Time O(N), Space O(1)\n * @param pos - Zero-based position from the front.\n * @param element - Element to insert.\n * @param [num] - Number of times to insert (default 1).\n * @returns True if inserted.\n */\n\n addAt(pos: number, element: E, num = 1): boolean {\n const length = this._length;\n rangeCheck(pos, 0, length);\n if (pos === 0) {\n while (num--) this.unshift(element);\n } else if (pos === this._length) {\n while (num--) this.push(element);\n } else {\n const arr: E[] = [];\n for (let i = pos; i < this._length; ++i) {\n const v = this.at(i);\n if (v !== undefined) arr.push(v);\n }\n this.cut(pos - 1, true);\n for (let i = 0; i < num; ++i) this.push(element);\n for (let i = 0; i < arr.length; ++i) this.push(arr[i]);\n }\n return true;\n }\n\n /**\n * Cut the deque to keep items up to index; optionally mutate in-place.\n * @remarks Time O(N), Space O(1)\n * @param pos - Last index to keep.\n * @param [isCutSelf] - When true, mutate this deque; otherwise return a new deque.\n * @returns This deque if in-place; otherwise a new deque of the prefix.\n */\n\n cut(pos: number, isCutSelf = false): Deque<E> {\n if (isCutSelf) {\n if (pos < 0) {\n this.clear();\n return this;\n }\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n this._bucketLast = bucketIndex;\n this._lastInBucket = indexInBucket;\n this._length = pos + 1;\n return this;\n } else {\n const newDeque = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n newDeque._setBucketSize(this._bucketSize);\n for (let i = 0; i <= pos; i++) {\n const v = this.at(i);\n if (v !== undefined) newDeque.push(v);\n }\n\n return newDeque;\n }\n }\n\n /**\n * Remove and/or insert elements at a position (array-like behavior).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default: length - start).\n * @param [items] - Elements to insert after `start`.\n * @returns A new deque containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount: number = this._length - start, ...items: E[]): this {\n rangeCheck(start, 0, this._length);\n if (deleteCount < 0) deleteCount = 0;\n if (start + deleteCount > this._length) deleteCount = this._length - start;\n\n const removed = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n removed._setBucketSize(this._bucketSize);\n for (let i = 0; i < deleteCount; i++) {\n const v = this.at(start + i);\n if (v !== undefined) removed.push(v);\n }\n\n const tail: E[] = [];\n for (let i = start + deleteCount; i < this._length; i++) {\n const v = this.at(i);\n if (v !== undefined) tail.push(v);\n }\n\n this.cut(start - 1, true);\n\n for (const it of items) this.push(it);\n\n for (const v of tail) this.push(v);\n\n return removed as unknown as this;\n }\n\n /**\n * Cut the deque to keep items from index onward; optionally mutate in-place.\n * @remarks Time O(N), Space O(1)\n * @param pos - First index to keep.\n * @param [isCutSelf] - When true, mutate this deque; otherwise return a new deque.\n * @returns This deque if in-place; otherwise a new deque of the suffix.\n */\n\n cutRest(pos: number, isCutSelf = false): Deque<E> {\n if (isCutSelf) {\n if (pos < 0) {\n return this;\n }\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n this._bucketFirst = bucketIndex;\n this._firstInBucket = indexInBucket;\n this._length = this._length - pos;\n return this;\n } else {\n const newDeque = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n newDeque._setBucketSize(this._bucketSize);\n if (pos < 0) pos = 0;\n for (let i = pos; i < this._length; i++) {\n const v = this.at(i);\n if (v !== undefined) newDeque.push(v);\n }\n return newDeque;\n }\n }\n\n /**\n * Delete the element at a given position.\n * @remarks Time O(N), Space O(1)\n * @param pos - Zero-based position from the front.\n * @returns Removed element or undefined.\n */\n\n deleteAt(pos: number): E | undefined {\n rangeCheck(pos, 0, this._length - 1);\n\n let deleted: E | undefined;\n if (pos === 0) {\n return this.shift();\n } else if (pos === this._length - 1) {\n deleted = this.last;\n this.pop();\n return deleted;\n } else {\n const length = this._length - 1;\n const { bucketIndex: targetBucket, indexInBucket: targetPointer } = this._getBucketAndPosition(pos);\n deleted = this._buckets[targetBucket][targetPointer];\n\n for (let i = pos; i < length; i++) {\n const { bucketIndex: curBucket, indexInBucket: curPointer } = this._getBucketAndPosition(i);\n const { bucketIndex: nextBucket, indexInBucket: nextPointer } = this._getBucketAndPosition(i + 1);\n this._buckets[curBucket][curPointer] = this._buckets[nextBucket][nextPointer];\n }\n\n this.pop();\n return deleted;\n }\n }\n\n /**\n * Delete the first occurrence of a value.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const size = this._length;\n if (size === 0) return false;\n let i = 0;\n let index = 0;\n while (i < size) {\n const oldElement = this.at(i);\n if (!this._equals(oldElement as E, element)) {\n this.setAt(index, oldElement!);\n index += 1;\n }\n i += 1;\n }\n this.cut(index - 1, true);\n return true;\n }\n\n /**\n * Delete the first element matching a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, deque) → boolean.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, deque: this) => boolean): boolean {\n for (let i = 0; i < this._length; i++) {\n const v = this.at(i);\n if (predicate(v as E, i, this)) {\n this.deleteAt(i);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Set the equality comparator used by delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This deque.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Reverse the deque by reversing buckets and pointers.\n * @remarks Time O(N), Space O(N)\n * @returns This deque.\n */\n\n reverse(): this {\n this._buckets.reverse().forEach(function (bucket) {\n bucket.reverse();\n });\n const { _bucketFirst, _bucketLast, _firstInBucket, _lastInBucket } = this;\n this._bucketFirst = this._bucketCount - _bucketLast - 1;\n this._bucketLast = this._bucketCount - _bucketFirst - 1;\n this._firstInBucket = this._bucketSize - _lastInBucket - 1;\n this._lastInBucket = this._bucketSize - _firstInBucket - 1;\n return this;\n }\n\n /**\n * Deduplicate consecutive equal elements in-place.\n * @remarks Time O(N), Space O(1)\n * @returns This deque.\n */\n\n unique(): this {\n if (this._length <= 1) {\n return this;\n }\n let index = 1;\n let prev = this.at(0);\n for (let i = 1; i < this._length; ++i) {\n const cur = this.at(i);\n if (!this._equals(cur as E, prev as E)) {\n prev = cur;\n this.setAt(index++, cur as E);\n }\n }\n this.cut(index - 1, true);\n return this;\n }\n\n /**\n * Trim unused buckets to fit exactly the active range.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n shrinkToFit(): void {\n if (this._length === 0) return;\n const newBuckets = [] as E[][];\n if (this._bucketFirst === this._bucketLast) return;\n else if (this._bucketFirst < this._bucketLast) {\n for (let i = this._bucketFirst; i <= this._bucketLast; ++i) {\n newBuckets.push(this._buckets[i]);\n }\n } else {\n for (let i = this._bucketFirst; i < this._bucketCount; ++i) {\n newBuckets.push(this._buckets[i]);\n }\n for (let i = 0; i <= this._bucketLast; ++i) {\n newBuckets.push(this._buckets[i]);\n }\n }\n this._bucketFirst = 0;\n this._bucketLast = newBuckets.length - 1;\n this._buckets = newBuckets;\n }\n\n /**\n * Deep clone this deque, preserving options.\n * @remarks Time O(N), Space O(N)\n * @returns A new deque with the same content and options.\n */\n\n clone(): this {\n return this._createLike<E, R>(this, {\n bucketSize: this.bucketSize,\n toElementFn: this.toElementFn,\n maxLen: this._maxLen\n }) as this;\n }\n\n /**\n * Filter elements into a new deque of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, deque) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new deque with kept elements.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setBucketSize(this._bucketSize);\n let index = 0;\n for (const el of this) {\n if (predicate.call(thisArg, el, index, this)) out.push(el);\n index++;\n }\n return out;\n }\n\n /**\n * Map elements into a new deque of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, deque) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new deque with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n out._setBucketSize(this._bucketSize);\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map elements into a new deque (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, deque) → newElement.\n * @param [options] - Options for the output deque (e.g., bucketSize, toElementFn, maxLen).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Deque with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: any\n ): Deque<EM, RM> {\n const out = this._createLike<EM, RM>([], {\n ...(options ?? {}),\n bucketSize: this._bucketSize,\n maxLen: this._maxLen\n }) as Deque<EM, RM>;\n let index = 0;\n for (const el of this) {\n const mv = thisArg === undefined ? callback(el, index, this) : callback.call(thisArg, el, index, this);\n out.push(mv);\n index++;\n }\n return out;\n }\n\n /**\n * (Protected) Set the internal bucket size.\n * @remarks Time O(1), Space O(1)\n * @param size - Bucket capacity to assign.\n * @returns void\n */\n\n protected _setBucketSize(size: number): void {\n this._bucketSize = size;\n }\n\n /**\n * (Protected) Iterate elements from front to back.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this._length; ++i) {\n const v = this.at(i);\n if (v !== undefined) yield v;\n }\n }\n\n /**\n * (Protected) Reallocate buckets to make room near the ends.\n * @remarks Time O(N), Space O(N)\n * @param [needBucketNum] - How many extra buckets to add; defaults to half of current.\n * @returns void\n */\n\n protected _reallocate(needBucketNum?: number) {\n const newBuckets = [] as E[][];\n const addBucketNum = needBucketNum || this._bucketCount >> 1 || 1;\n for (let i = 0; i < addBucketNum; ++i) {\n newBuckets[i] = new Array(this._bucketSize);\n }\n for (let i = this._bucketFirst; i < this._bucketCount; ++i) {\n newBuckets[newBuckets.length] = this._buckets[i];\n }\n for (let i = 0; i < this._bucketLast; ++i) {\n newBuckets[newBuckets.length] = this._buckets[i];\n }\n newBuckets[newBuckets.length] = [...this._buckets[this._bucketLast]];\n this._bucketFirst = addBucketNum;\n this._bucketLast = newBuckets.length - 1;\n for (let i = 0; i < addBucketNum; ++i) {\n newBuckets[newBuckets.length] = new Array(this._bucketSize);\n }\n this._buckets = newBuckets;\n this._bucketCount = newBuckets.length;\n }\n\n /**\n * (Protected) Translate a logical position to bucket/offset.\n * @remarks Time O(1), Space O(1)\n * @param pos - Zero-based position.\n * @returns An object containing bucketIndex and indexInBucket.\n */\n\n protected _getBucketAndPosition(pos: number) {\n let bucketIndex: number;\n let indexInBucket: number;\n\n const overallIndex = this._firstInBucket + pos;\n bucketIndex = this._bucketFirst + Math.floor(overallIndex / this._bucketSize);\n\n if (bucketIndex >= this._bucketCount) {\n bucketIndex -= this._bucketCount;\n }\n\n indexInBucket = ((overallIndex + 1) % this._bucketSize) - 1;\n if (indexInBucket < 0) {\n indexInBucket = this._bucketSize - 1;\n }\n\n return { bucketIndex, indexInBucket };\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind deque instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>,\n options?: DequeOptions<E, R>\n ) => this;\n return new Ctor([], options as DequeOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind deque seeded by elements.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new deque.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Deque instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: IterableWithSizeOrLength<T> | IterableWithSizeOrLength<RR> = [],\n options?: DequeOptions<T, RR>\n ): any {\n const Ctor = this.constructor as new (\n elements?: IterableWithSizeOrLength<T> | IterableWithSizeOrLength<RR>,\n options?: DequeOptions<T, RR>\n ) => any;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from back to front.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n for (let i = this._length - 1; i > -1; i--) {\n const v = this.at(i);\n if (v !== undefined) yield v;\n }\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: Each node in a heap follows a specific order property, which varies depending on the type of heap:\n * Max Heap: The value of each parent node is greater than or equal to the value of its children.\n * Min Heap: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n * // basic Heap creation and add operation\n * // Create a min heap (default)\n * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);\n *\n * // Verify size\n * console.log(minHeap.size); // 6;\n *\n * // Add new element\n * minHeap.add(4);\n * console.log(minHeap.size); // 7;\n *\n * // Min heap property: smallest element at root\n * const min = minHeap.peek();\n * console.log(min); // 1;\n * @example\n * // Heap with custom comparator (MaxHeap behavior)\n * interface Task {\n * id: number;\n * priority: number;\n * name: string;\n * }\n *\n * // Custom comparator for max heap behavior (higher priority first)\n * const tasks: Task[] = [\n * { id: 1, priority: 5, name: 'Email' },\n * { id: 2, priority: 3, name: 'Chat' },\n * { id: 3, priority: 8, name: 'Alert' }\n * ];\n *\n * const maxHeap = new Heap(tasks, {\n * comparator: (a: Task, b: Task) => b.priority - a.priority\n * });\n *\n * console.log(maxHeap.size); // 3;\n *\n * // Peek returns highest priority task\n * const topTask = maxHeap.peek();\n * console.log(topTask?.priority); // 8;\n * console.log(topTask?.name); // 'Alert';\n * @example\n * // Heap for event processing with priority\n * interface Event {\n * id: number;\n * type: 'critical' | 'warning' | 'info';\n * timestamp: number;\n * message: string;\n * }\n *\n * // Custom priority: critical > warning > info\n * const priorityMap = { critical: 3, warning: 2, info: 1 };\n *\n * const eventHeap = new Heap<Event>([], {\n * comparator: (a: Event, b: Event) => {\n * const priorityA = priorityMap[a.type];\n * const priorityB = priorityMap[b.type];\n * return priorityB - priorityA; // Higher priority first\n * }\n * });\n *\n * // Add events in random order\n * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });\n * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });\n * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });\n * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });\n * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });\n *\n * console.log(eventHeap.size); // 5;\n *\n * // Process events by priority (critical first)\n * const processedOrder: Event[] = [];\n * while (eventHeap.size > 0) {\n * const event = eventHeap.poll();\n * if (event) {\n * processedOrder.push(event);\n * }\n * }\n *\n * // Verify critical events came first\n * console.log(processedOrder[0].type); // 'critical';\n * console.log(processedOrder[1].type); // 'critical';\n * console.log(processedOrder[2].type); // 'warning';\n * console.log(processedOrder[3].type); // 'info';\n * console.log(processedOrder[4].type); // 'info';\n *\n * // Verify O(log n) operations\n * const newHeap = new Heap<number>([5, 3, 7, 1]);\n *\n * // Add - O(log n)\n * newHeap.add(2);\n * console.log(newHeap.size); // 5;\n *\n * // Poll - O(log n)\n * const removed = newHeap.poll();\n * console.log(removed); // 1;\n *\n * // Peek - O(1)\n * const top = newHeap.peek();\n * console.log(top); // 2;\n * @example\n * // Use Heap to solve top k problems\n * function topKElements(arr: number[], k: number): number[] {\n * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap\n * arr.forEach(num => {\n * heap.add(num);\n * if (heap.size > k) heap.poll(); // Keep the heap size at K\n * });\n * return heap.toArray();\n * }\n *\n * const numbers = [10, 30, 20, 5, 15, 25];\n * console.log(topKElements(numbers, 3)); // [15, 10, 5];\n * @example\n * // Use Heap to dynamically maintain the median\n * class MedianFinder {\n * private low: MaxHeap<number>; // Max heap, stores the smaller half\n * private high: MinHeap<number>; // Min heap, stores the larger half\n *\n * constructor() {\n * this.low = new MaxHeap<number>([]);\n * this.high = new MinHeap<number>([]);\n * }\n *\n * addNum(num: number): void {\n * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);\n * else this.high.add(num);\n *\n * // Balance heaps\n * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);\n * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);\n * }\n *\n * findMedian(): number {\n * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;\n * return this.low.peek()!;\n * }\n * }\n *\n * const medianFinder = new MedianFinder();\n * medianFinder.addNum(10);\n * console.log(medianFinder.findMedian()); // 10;\n * medianFinder.addNum(20);\n * console.log(medianFinder.findMedian()); // 15;\n * medianFinder.addNum(30);\n * console.log(medianFinder.findMedian()); // 20;\n * medianFinder.addNum(40);\n * console.log(medianFinder.findMedian()); // 25;\n * medianFinder.addNum(50);\n * console.log(medianFinder.findMedian()); // 30;\n * @example\n * // Use Heap for load balancing\n * function loadBalance(requests: number[], servers: number): number[] {\n * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap\n * const serverLoads = new Array(servers).fill(0);\n *\n * for (let i = 0; i < servers; i++) {\n * serverHeap.add({ id: i, load: 0 });\n * }\n *\n * requests.forEach(req => {\n * const server = serverHeap.poll()!;\n * serverLoads[server.id] += req;\n * server.load += req;\n * serverHeap.add(server); // The server after updating the load is re-entered into the heap\n * });\n *\n * return serverLoads;\n * }\n *\n * const requests = [5, 2, 8, 3, 7];\n * console.log(loadBalance(requests, 3)); // [12, 8, 5];\n * @example\n * // Use Heap to schedule tasks\n * type Task = [string, number];\n *\n * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {\n * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap\n * const allocation = new Map<number, Task[]>();\n *\n * // Initialize the load on each machine\n * for (let i = 0; i < machines; i++) {\n * machineHeap.add({ id: i, load: 0 });\n * allocation.set(i, []);\n * }\n *\n * // Assign tasks\n * tasks.forEach(([task, load]) => {\n * const machine = machineHeap.poll()!;\n * allocation.get(machine.id)!.push([task, load]);\n * machine.load += load;\n * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap\n * });\n *\n * return allocation;\n * }\n *\n * const tasks: Task[] = [\n * ['Task1', 3],\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task4', 5],\n * ['Task5', 4]\n * ];\n * const expectedMap = new Map<number, Task[]>();\n * expectedMap.set(0, [\n * ['Task1', 3],\n * ['Task4', 5]\n * ]);\n * expectedMap.set(1, [\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task5', 4]\n * ]);\n * console.log(scheduleTasks(tasks, 2)); // expectedMap;\n */\nexport class Heap<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is;\n\n /**\n * Create a Heap and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw values if toElementFn is set).\n * @param [options] - Options such as comparator and toElementFn.\n * @returns New Heap instance.\n */\n\n constructor(elements: Iterable<E | R> = [], options?: HeapOptions<E, R>) {\n super(options);\n\n if (options) {\n const { comparator } = options;\n if (comparator) this._comparator = comparator;\n }\n\n this.addMany(elements as Iterable<E | R>);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of the heap.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Heap size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Get the last leaf element.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get leaf(): E | undefined {\n return this.elements[this.size - 1] ?? undefined;\n }\n\n /**\n * Create a heap of the same class from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template R\n * @template S\n * @param [elements] - Iterable of elements or raw records.\n * @param [options] - Heap options including comparator.\n * @returns A new heap instance of this class.\n */\n\n static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(\n this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,\n elements?: Iterable<T | R>,\n options?: HeapOptions<T, R>\n ): S {\n return new this(elements, options);\n }\n\n /**\n * Build a Heap from an iterable in linear time given a comparator.\n * @remarks Time O(N), Space O(N)\n * @template EE\n * @template RR\n * @param elements - Iterable of elements.\n * @param options - Heap options including comparator.\n * @returns A new Heap built from elements.\n */\n\n static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {\n return new Heap<EE, RR>(elements, options);\n }\n\n /**\n * Insert an element.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns True.\n */\n\n add(element: E): boolean {\n this._elements.push(element);\n return this._bubbleUp(this.elements.length - 1);\n }\n\n /**\n * Insert many elements from an iterable.\n * @remarks Time O(N log N), Space O(1)\n * @param elements - Iterable of elements or raw values.\n * @returns Array of per-element success flags.\n */\n\n addMany(elements: Iterable<E | R>): boolean[] {\n const flags: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n const ok = this.add(this.toElementFn(el as R));\n flags.push(ok);\n } else {\n const ok = this.add(el as E);\n flags.push(ok);\n }\n }\n return flags;\n }\n\n /**\n * Remove and return the top element.\n * @remarks Time O(log N), Space O(1)\n * @returns Top element or undefined.\n */\n\n poll(): E | undefined {\n if (this.elements.length === 0) return;\n const value = this.elements[0];\n const last = this.elements.pop()!;\n if (this.elements.length) {\n this.elements[0] = last;\n this._sinkDown(0, this.elements.length >> 1);\n }\n return value;\n }\n\n /**\n * Get the current top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.elements[0];\n }\n\n /**\n * Check whether the heap is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Remove all elements.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Replace the backing array and rebuild the heap.\n * @remarks Time O(N), Space O(N)\n * @param elements - Iterable used to refill the heap.\n * @returns Array of per-node results from fixing steps.\n */\n\n refill(elements: Iterable<E>): boolean[] {\n this._elements = Array.from(elements);\n return this.fix();\n }\n\n /**\n * Check if an equal element exists in the heap.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to search for.\n * @returns True if found.\n */\n\n override has(element: E): boolean {\n for (const el of this.elements) if (this._equals(el, element)) return true;\n return false;\n }\n\n /**\n * Delete one occurrence of an element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to delete.\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n let index = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (this._equals(this.elements[i], element)) {\n index = i;\n break;\n }\n }\n if (index < 0) return false;\n if (index === 0) {\n this.poll();\n } else if (index === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(index, 1, this.elements.pop()!);\n this._bubbleUp(index);\n this._sinkDown(index, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Delete the first element that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (element, index, heap) → boolean.\n * @returns True if an element was removed.\n */\n\n deleteBy(predicate: (element: E, index: number, heap: this) => boolean): boolean {\n let idx = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n idx = i;\n break;\n }\n }\n if (idx < 0) return false;\n if (idx === 0) {\n this.poll();\n } else if (idx === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(idx, 1, this.elements.pop()!);\n this._bubbleUp(idx);\n this._sinkDown(idx, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Set the equality comparator used by has/delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This heap.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Traverse the binary heap as a complete binary tree and collect elements.\n * @remarks Time O(N), Space O(H)\n * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.\n * @returns Array of visited elements.\n */\n\n dfs(order: DFSOrderPattern = 'PRE'): E[] {\n const result: E[] = [];\n const _dfs = (index: number) => {\n const left = 2 * index + 1,\n right = left + 1;\n if (index < this.size) {\n if (order === 'IN') {\n _dfs(left);\n result.push(this.elements[index]);\n _dfs(right);\n } else if (order === 'PRE') {\n result.push(this.elements[index]);\n _dfs(left);\n _dfs(right);\n } else if (order === 'POST') {\n _dfs(left);\n _dfs(right);\n result.push(this.elements[index]);\n }\n }\n };\n _dfs(0);\n return result;\n }\n\n /**\n * Restore heap order bottom-up (heapify in-place).\n * @remarks Time O(N), Space O(1)\n * @returns Array of per-node results from fixing steps.\n */\n\n fix(): boolean[] {\n const results: boolean[] = [];\n for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {\n results.push(this._sinkDown(i, this.elements.length >> 1));\n }\n return results;\n }\n\n /**\n * Return all elements in ascending order by repeatedly polling.\n * @remarks Time O(N log N), Space O(N)\n * @returns Sorted array of elements.\n */\n\n sort(): E[] {\n const visited: E[] = [];\n const cloned = this._createInstance();\n for (const x of this.elements) cloned.add(x);\n while (!cloned.isEmpty()) {\n const top = cloned.poll();\n if (top !== undefined) visited.push(top);\n }\n return visited;\n }\n\n /**\n * Deep clone this heap.\n * @remarks Time O(N), Space O(N)\n * @returns A new heap with the same elements.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this.elements) next.add(x);\n return next;\n }\n\n /**\n * Filter elements into a new heap of the same class.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Predicate (element, index, heap) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with the kept elements.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n if (thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {\n out.add(x);\n } else {\n i++;\n }\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of possibly different element type.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, heap) → newElement.\n * @param options - Options for the output heap, including comparator for EM.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options: HeapOptions<EM, RM> & { comparator: Comparator<EM> },\n thisArg?: unknown\n ): Heap<EM, RM> {\n const { comparator, toElementFn, ...rest } = options ?? {};\n if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');\n const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of the same element type.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Mapping function (element, index, heap) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n protected _DEFAULT_COMPARATOR = (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError('When comparing object types, define a custom comparator in options.');\n }\n if ((a as unknown as number) > (b as unknown as number)) return 1;\n if ((a as unknown as number) < (b as unknown as number)) return -1;\n return 0;\n };\n\n protected _comparator: Comparator<E> = this._DEFAULT_COMPARATOR; /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n\n get comparator() {\n return this._comparator;\n }\n\n protected *_getIterator(): IterableIterator<E> {\n for (const element of this.elements) yield element;\n }\n\n protected _bubbleUp(index: number): boolean {\n const element = this.elements[index];\n while (index > 0) {\n const parent = (index - 1) >> 1;\n const parentItem = this.elements[parent];\n if (this.comparator(parentItem, element) <= 0) break;\n this.elements[index] = parentItem;\n index = parent;\n }\n this.elements[index] = element;\n return true;\n }\n\n protected _sinkDown(index: number, halfLength: number): boolean {\n const element = this.elements[index];\n while (index < halfLength) {\n let left = (index << 1) | 1;\n const right = left + 1;\n let minItem = this.elements[left];\n if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {\n left = right;\n minItem = this.elements[right];\n }\n if (this.comparator(minItem, element) >= 0) break;\n this.elements[index] = minItem;\n index = left;\n }\n this.elements[index] = element;\n return true;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options to override comparator or toElementFn.\n * @returns A like-kind empty heap instance.\n */\n\n protected _createInstance(options?: HeapOptions<E, R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...(options ?? {}) });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind instance seeded by elements.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable of elements or raw values to seed.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind heap instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: HeapOptions<EM, RM>\n ): Heap<EM, RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Heap<EM, RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind heap instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind heap instance.\n */\n\n protected _spawnLike<EM, RM>(options?: HeapOptions<EM, RM>): Heap<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\n/**\n * Node container used by FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class FibonacciHeapNode<E> {\n element: E;\n degree: number;\n left?: FibonacciHeapNode<E>;\n right?: FibonacciHeapNode<E>;\n child?: FibonacciHeapNode<E>;\n parent?: FibonacciHeapNode<E>;\n marked: boolean;\n\n constructor(element: E, degree = 0) {\n this.element = element;\n this.degree = degree;\n this.marked = false;\n }\n}\n\n/**\n * Fibonacci heap (min-heap) optimized for fast merges and amortized operations.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @example examples will be generated by unit test\n */\nexport class FibonacciHeap<E> {\n /**\n * Create a FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @param [comparator] - Comparator to order elements (min-heap by default).\n * @returns New FibonacciHeap instance.\n */\n\n constructor(comparator?: Comparator<E>) {\n this.clear();\n this._comparator = comparator || this._defaultComparator;\n if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');\n }\n\n protected _root?: FibonacciHeapNode<E>;\n\n /**\n * Get the circular root list head.\n * @remarks Time O(1), Space O(1)\n * @returns Root node or undefined.\n */\n\n get root(): FibonacciHeapNode<E> | undefined {\n return this._root;\n }\n\n protected _size = 0;\n get size(): number {\n return this._size;\n }\n\n protected _min?: FibonacciHeapNode<E>;\n\n /**\n * Get the current minimum node.\n * @remarks Time O(1), Space O(1)\n * @returns Min node or undefined.\n */\n\n get min(): FibonacciHeapNode<E> | undefined {\n return this._min;\n }\n\n protected _comparator: Comparator<E>;\n get comparator(): Comparator<E> {\n return this._comparator;\n }\n\n clear(): void {\n this._root = undefined;\n this._min = undefined;\n this._size = 0;\n }\n\n add(element: E): boolean {\n this.push(element);\n return true;\n }\n\n /**\n * Push an element into the root list.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns This heap.\n */\n\n push(element: E): this {\n const node = this.createNode(element);\n node.left = node;\n node.right = node;\n this.mergeWithRoot(node);\n if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;\n this._size++;\n return this;\n }\n\n peek(): E | undefined {\n return this.min ? this.min.element : undefined;\n }\n\n /**\n * Collect nodes from a circular doubly linked list starting at head.\n * @remarks Time O(K), Space O(K)\n * @param [head] - Start node of the circular list.\n * @returns Array of nodes from the list.\n */\n\n consumeLinkedList(head?: FibonacciHeapNode<E>): FibonacciHeapNode<E>[] {\n const elements: FibonacciHeapNode<E>[] = [];\n if (!head) return elements;\n let node: FibonacciHeapNode<E> | undefined = head;\n let started = false;\n while (true) {\n if (node === head && started) break;\n else if (node === head) started = true;\n elements.push(node!);\n node = node!.right;\n }\n return elements;\n }\n\n /**\n * Insert a node into a parent's child list (circular).\n * @remarks Time O(1), Space O(1)\n * @param parent - Parent node.\n * @param node - Child node to insert.\n * @returns void\n */\n\n mergeWithChild(parent: FibonacciHeapNode<E>, node: FibonacciHeapNode<E>): void {\n if (!parent.child) parent.child = node;\n else {\n node.right = parent.child.right;\n node.left = parent.child;\n parent.child.right!.left = node;\n parent.child.right = node;\n }\n }\n\n poll(): E | undefined {\n return this.pop();\n }\n\n /**\n * Remove and return the minimum element, consolidating the root list.\n * @remarks Time O(log N) amortized, Space O(1)\n * @returns Minimum element or undefined.\n */\n\n pop(): E | undefined {\n if (this._size === 0) return undefined;\n const z = this.min!;\n if (z.child) {\n const elements = this.consumeLinkedList(z.child);\n for (const node of elements) {\n this.mergeWithRoot(node);\n node.parent = undefined;\n }\n }\n this.removeFromRoot(z);\n if (z === z.right) {\n this._min = undefined;\n this._root = undefined;\n } else {\n this._min = z.right;\n this._consolidate();\n }\n this._size--;\n return z.element;\n }\n\n /**\n * Meld another heap into this heap.\n * @remarks Time O(1), Space O(1)\n * @param heapToMerge - Another FibonacciHeap to meld into this one.\n * @returns void\n */\n\n merge(heapToMerge: FibonacciHeap<E>): void {\n if (heapToMerge.size === 0) return;\n if (this.root && heapToMerge.root) {\n const thisRoot = this.root,\n otherRoot = heapToMerge.root;\n const thisRootRight = thisRoot.right!,\n otherRootLeft = otherRoot.left!;\n thisRoot.right = otherRoot;\n otherRoot.left = thisRoot;\n thisRootRight.left = otherRootLeft;\n otherRootLeft.right = thisRootRight;\n } else if (!this.root && heapToMerge.root) {\n this._root = heapToMerge.root;\n }\n if (!this.min || (heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0)) {\n this._min = heapToMerge.min;\n }\n this._size += heapToMerge.size;\n heapToMerge.clear();\n }\n\n createNode(element: E): FibonacciHeapNode<E> {\n return new FibonacciHeapNode<E>(element);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n protected _defaultComparator(a: E, b: E): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n protected mergeWithRoot(node: FibonacciHeapNode<E>): void {\n if (!this.root) this._root = node;\n else {\n node.right = this.root.right;\n node.left = this.root;\n this.root.right!.left = node;\n this.root.right = node;\n }\n }\n\n protected removeFromRoot(node: FibonacciHeapNode<E>): void {\n if (this.root === node) this._root = node.right;\n if (node.left) node.left.right = node.right;\n if (node.right) node.right.left = node.left;\n }\n\n protected _link(y: FibonacciHeapNode<E>, x: FibonacciHeapNode<E>): void {\n this.removeFromRoot(y);\n y.left = y;\n y.right = y;\n this.mergeWithChild(x, y);\n x.degree++;\n y.parent = x;\n }\n\n protected _consolidate(): void {\n const A: (FibonacciHeapNode<E> | undefined)[] = new Array(this._size);\n const elements = this.consumeLinkedList(this.root);\n let x: FibonacciHeapNode<E> | undefined,\n y: FibonacciHeapNode<E> | undefined,\n d: number,\n t: FibonacciHeapNode<E> | undefined;\n\n for (const node of elements) {\n x = node;\n d = x.degree;\n while (A[d]) {\n y = A[d] as FibonacciHeapNode<E>;\n if (this.comparator(x.element, y.element) > 0) {\n t = x;\n x = y;\n y = t;\n }\n this._link(y, x);\n A[d] = undefined;\n d++;\n }\n A[d] = x;\n }\n\n for (let i = 0; i < A.length; i++) {\n if (A[i] && (!this.min || this.comparator(A[i]!.element, this.min.element) <= 0)) this._min = A[i]!;\n }\n }\n}\n","/**\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Max-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: The value of each parent node is greater than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MaxHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a max-heap. For objects, supply a custom comparator.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","/**\n * @remarks Time O(n log n), Space O(n).\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Min-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. MinHeap Properties: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. MinHeap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MinHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a min-heap.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { DijkstraResult, EntryCallback, GraphOptions, VertexKey } from '../../types';\nimport { uuidV4 } from '../../utils';\nimport { IterableEntryBase } from '../base';\nimport { IGraph } from '../../interfaces';\nimport { Heap } from '../heap';\nimport { Queue } from '../queue';\n\nexport abstract class AbstractVertex<V = any> {\n key: VertexKey;\n value: V | undefined;\n\n protected constructor(key: VertexKey, value?: V) {\n this.key = key;\n this.value = value;\n }\n}\n\nexport abstract class AbstractEdge<E = any> {\n value: E | undefined;\n weight: number;\n\n protected constructor(weight?: number, value?: E) {\n this.weight = weight !== undefined ? weight : 1;\n this.value = value;\n this._hashCode = uuidV4();\n }\n\n protected _hashCode: string;\n\n get hashCode(): string {\n return this._hashCode;\n }\n}\n\n/**\n * Abstract graph over vertices and edges.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex subclass (extends AbstractVertex<V>).\n * @template EO - Concrete edge subclass (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example examples will be generated by unit test\n */\nexport abstract class AbstractGraph<\n V = any,\n E = any,\n VO extends AbstractVertex<V> = AbstractVertex<V>,\n EO extends AbstractEdge<E> = AbstractEdge<E>\n>\n extends IterableEntryBase<VertexKey, V | undefined>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct a graph with runtime defaults.\n * @param options - `GraphOptions<V>` in `options.graph` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<Record<string, unknown>>) {\n super();\n const graph = (options as any)?.graph as GraphOptions<V> | undefined;\n this._options = { defaultEdgeWeight: 1, ...(graph ?? {}) };\n }\n\n protected _options: GraphOptions<V> = { defaultEdgeWeight: 1 };\n\n get options(): Readonly<GraphOptions<V>> {\n return this._options;\n }\n\n protected _vertexMap: Map<VertexKey, VO> = new Map<VertexKey, VO>();\n\n get vertexMap(): Map<VertexKey, VO> {\n return this._vertexMap;\n }\n\n set vertexMap(v: Map<VertexKey, VO>) {\n this._vertexMap = v;\n }\n\n get size(): number {\n return this._vertexMap.size;\n }\n\n /**\n * Create a new vertex instance (implementation specific).\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n abstract createVertex(key: VertexKey, value?: V): VO;\n\n /**\n * Create a new edge instance (implementation specific).\n * @param srcOrV1 - Source/endpoint A key.\n * @param destOrV2 - Destination/endpoint B key.\n * @param weight - Edge weight (defaults may apply).\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n abstract createEdge(srcOrV1: VertexKey, destOrV2: VertexKey, weight?: number, value?: E): EO;\n\n /**\n * Delete an edge by instance.\n * @param edge - Edge instance.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract deleteEdge(edge: EO): EO | undefined;\n\n /**\n * Get an edge between two vertices if present.\n * @param srcOrKey - Source/endpoint A vertex or key.\n * @param destOrKey - Destination/endpoint B vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract getEdge(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined;\n\n /**\n * Degree of a vertex in this graph model.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer degree.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract degreeOf(vertexOrKey: VO | VertexKey): number;\n\n /**\n * All edges in the graph (unique, order not guaranteed).\n * @returns Array of edges.\n * @remarks Time O(E), Space O(E)\n */\n abstract edgeSet(): EO[];\n\n /**\n * Incident edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg), Space O(deg)\n */\n abstract edgesOf(vertexOrKey: VO | VertexKey): EO[];\n\n /**\n * One-step neighbors of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg), Space O(deg)\n */\n abstract getNeighbors(vertexOrKey: VO | VertexKey): VO[];\n\n /**\n * Resolve endpoints of an edge to vertex instances.\n * @param edge - Edge instance.\n * @returns `[v1, v2]` or `undefined` if missing.\n * @remarks Time O(1), Space O(1)\n */\n abstract getEndsOfEdge(edge: EO): [VO, VO] | undefined;\n\n /**\n * Get vertex instance by key.\n * @param vertexKey - Vertex key.\n * @returns Vertex instance or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n getVertex(vertexKey: VertexKey): VO | undefined {\n return this._vertexMap.get(vertexKey) || undefined;\n }\n\n /**\n * Whether a vertex exists.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if present, otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n hasVertex(vertexOrKey: VO | VertexKey): boolean {\n return this._vertexMap.has(this._getVertexKey(vertexOrKey));\n }\n\n addVertex(vertex: VO): boolean;\n\n addVertex(key: VertexKey, value?: V): boolean;\n\n /**\n * Add a vertex by key/value or by pre-built vertex.\n * @param keyOrVertex - Vertex key or existing vertex instance.\n * @param value - Optional payload.\n * @returns `true` if inserted; `false` when key already exists.\n * @remarks Time O(1) avg, Space O(1)\n */\n addVertex(keyOrVertex: VertexKey | VO, value?: V): boolean {\n if (keyOrVertex instanceof AbstractVertex) {\n return this._addVertex(keyOrVertex);\n } else {\n const newVertex = this.createVertex(keyOrVertex, value);\n return this._addVertex(newVertex);\n }\n }\n\n /**\n * Type guard: check if a value is a valid vertex key.\n * @param potentialKey - Value to test.\n * @returns `true` if string/number; else `false`.\n * @remarks Time O(1), Space O(1)\n */\n isVertexKey(potentialKey: any): potentialKey is VertexKey {\n const potentialKeyType = typeof potentialKey;\n return potentialKeyType === 'string' || potentialKeyType === 'number';\n }\n\n /**\n * Delete a vertex and its incident edges.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if removed; otherwise `false`.\n * @remarks Time O(deg), Space O(1)\n */\n abstract deleteVertex(vertexOrKey: VO | VertexKey): boolean;\n\n /**\n * Delete multiple vertices.\n * @param vertexMap - Array of vertices or keys.\n * @returns `true` if any vertex was removed.\n * @remarks Time O(sum(deg)), Space O(1)\n */\n removeManyVertices(vertexMap: VO[] | VertexKey[]): boolean {\n const removed: boolean[] = [];\n for (const v of vertexMap) {\n removed.push(this.deleteVertex(v));\n }\n return removed.length > 0;\n }\n\n /**\n * Whether an edge exists between two vertices.\n * @param v1 - Endpoint A vertex or key.\n * @param v2 - Endpoint B vertex or key.\n * @returns `true` if present; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n hasEdge(v1: VertexKey | VO, v2: VertexKey | VO): boolean {\n const edge = this.getEdge(v1, v2);\n return !!edge;\n }\n\n addEdge(edge: EO): boolean;\n\n addEdge(src: VO | VertexKey, dest: VO | VertexKey, weight?: number, value?: E): boolean;\n\n /**\n * Add an edge by instance or by `(src, dest, weight?, value?)`.\n * @param srcOrEdge - Edge instance or source vertex/key.\n * @param dest - Destination vertex/key (when adding by pair).\n * @param weight - Edge weight.\n * @param value - Edge payload.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n addEdge(srcOrEdge: VO | VertexKey | EO, dest?: VO | VertexKey, weight?: number, value?: E): boolean {\n if (srcOrEdge instanceof AbstractEdge) {\n return this._addEdge(srcOrEdge);\n } else {\n if (dest instanceof AbstractVertex || typeof dest === 'string' || typeof dest === 'number') {\n if (!(this.hasVertex(srcOrEdge) && this.hasVertex(dest))) return false;\n if (srcOrEdge instanceof AbstractVertex) srcOrEdge = srcOrEdge.key;\n if (dest instanceof AbstractVertex) dest = dest.key;\n const newEdge = this.createEdge(srcOrEdge, dest, weight, value);\n return this._addEdge(newEdge);\n } else {\n throw new Error('dest must be a Vertex or vertex key while srcOrEdge is an Edge');\n }\n }\n }\n\n /**\n * Set the weight of an existing edge.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @param weight - New weight.\n * @returns `true` if updated; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n setEdgeWeight(srcOrKey: VertexKey | VO, destOrKey: VertexKey | VO, weight: number): boolean {\n const edge = this.getEdge(srcOrKey, destOrKey);\n if (edge) {\n edge.weight = weight;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Enumerate simple paths up to a limit.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param limit - Maximum number of paths to collect.\n * @returns Array of paths (each path is an array of vertices).\n * @remarks Time O(paths) worst-case exponential, Space O(V + paths)\n */\n getAllPathsBetween(v1: VO | VertexKey, v2: VO | VertexKey, limit = 1000): VO[][] {\n const paths: VO[][] = [];\n const vertex1 = this._getVertex(v1);\n const vertex2 = this._getVertex(v2);\n\n if (!(vertex1 && vertex2)) {\n return [];\n }\n\n const stack: { vertex: VO; path: VO[] }[] = [];\n stack.push({ vertex: vertex1, path: [vertex1] });\n\n while (stack.length > 0) {\n const { vertex, path } = stack.pop()!;\n\n if (vertex === vertex2) {\n paths.push(path);\n if (paths.length >= limit) return paths;\n }\n\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n if (!path.includes(neighbor)) {\n const newPath = [...path, neighbor];\n stack.push({ vertex: neighbor, path: newPath });\n }\n }\n }\n return paths;\n }\n\n /**\n * Sum the weights along a vertex path.\n * @param path - Sequence of vertices.\n * @returns Path weight sum (0 if empty or edge missing).\n * @remarks Time O(L), Space O(1) where L is path length\n */\n getPathSumWeight(path: VO[]): number {\n let sum = 0;\n for (let i = 0; i < path.length; i++) {\n sum += this.getEdge(path[i], path[i + 1])?.weight || 0;\n }\n return sum;\n }\n\n /**\n * Minimum hops/weight between two vertices.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param isWeight - If `true`, compare by path weight; otherwise by hop count.\n * @returns Minimum cost or `undefined` if missing/unreachable.\n * @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)\n */\n getMinCostBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): number | undefined {\n if (isWeight === undefined) isWeight = false;\n\n if (isWeight) {\n const allPaths = this.getAllPathsBetween(v1, v2);\n let min = Number.MAX_SAFE_INTEGER;\n for (const path of allPaths) {\n min = Math.min(this.getPathSumWeight(path), min);\n }\n return min;\n } else {\n const vertex2 = this._getVertex(v2);\n const vertex1 = this._getVertex(v1);\n if (!(vertex1 && vertex2)) {\n return undefined;\n }\n\n const visited: Map<VO, boolean> = new Map();\n const queue = new Queue<VO>([vertex1]);\n visited.set(vertex1, true);\n let cost = 0;\n while (queue.length > 0) {\n for (let i = 0, layerSize = queue.length; i < layerSize; i++) {\n const cur = queue.shift();\n if (cur === vertex2) {\n return cost;\n }\n\n if (cur !== undefined) {\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n visited.set(neighbor, true);\n queue.push(neighbor);\n }\n }\n }\n }\n cost++;\n }\n return undefined;\n }\n }\n\n /**\n * Minimum path (as vertex sequence) between two vertices.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param isWeight - If `true`, compare by path weight; otherwise by hop count.\n * @param isDFS - For weighted mode only: if `true`, brute-force all paths; if `false`, use Dijkstra.\n * @returns Vertex sequence, or `undefined`/empty when unreachable depending on branch.\n * @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)\n */\n getMinPathBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean, isDFS = false): VO[] | undefined {\n if (isWeight === undefined) isWeight = false;\n\n if (isWeight) {\n if (isDFS) {\n const allPaths = this.getAllPathsBetween(v1, v2, 10000);\n let min = Number.MAX_SAFE_INTEGER;\n let minIndex = -1;\n let index = 0;\n for (const path of allPaths) {\n const pathSumWeight = this.getPathSumWeight(path);\n if (pathSumWeight < min) {\n min = pathSumWeight;\n minIndex = index;\n }\n index++;\n }\n return allPaths[minIndex] || undefined;\n } else {\n /**\n * Dijkstra (binary-heap) shortest paths for non-negative weights.\n * @param src - Source vertex or key.\n * @param dest - Optional destination for early stop.\n * @param getMinDist - If `true`, compute global minimum distance.\n * @param genPaths - If `true`, also generate path arrays.\n * @returns Result bag or `undefined` if source missing.\n * @remarks Time O((V + E) log V), Space O(V + E)\n */\n return this.dijkstra(v1, v2, true, true)?.minPath ?? [];\n }\n } else {\n let minPath: VO[] = [];\n const vertex1 = this._getVertex(v1);\n const vertex2 = this._getVertex(v2);\n if (!(vertex1 && vertex2)) return [];\n\n const dfs = (cur: VO, dest: VO, visiting: Set<VO>, path: VO[]) => {\n visiting.add(cur);\n if (cur === dest) {\n minPath = [vertex1, ...path];\n return;\n }\n\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!visiting.has(neighbor)) {\n path.push(neighbor);\n dfs(neighbor, dest, visiting, path);\n path.pop();\n }\n }\n\n visiting.delete(cur);\n };\n\n dfs(vertex1, vertex2, new Set<VO>(), []);\n return minPath;\n }\n }\n\n /**\n * Dijkstra without heap (array-based selection).\n * @param src - Source vertex or key.\n * @param dest - Optional destination for early stop.\n * @param getMinDist - If `true`, compute global minimum distance.\n * @param genPaths - If `true`, also generate path arrays.\n * @returns Result bag or `undefined` if source missing.\n * @remarks Time O(V^2 + E), Space O(V + E)\n */\n dijkstraWithoutHeap(\n src: VO | VertexKey,\n dest: VO | VertexKey | undefined = undefined,\n getMinDist: boolean = false,\n genPaths: boolean = false\n ): DijkstraResult<VO> | undefined {\n let minDist = Number.MAX_SAFE_INTEGER;\n let minDest: VO | undefined = undefined;\n let minPath: VO[] = [];\n const paths: VO[][] = [];\n\n const vertexMap = this._vertexMap;\n const distMap: Map<VO, number> = new Map();\n const seen: Set<VO> = new Set();\n const preMap: Map<VO, VO | undefined> = new Map();\n const srcVertex = this._getVertex(src);\n\n const destVertex = dest ? this._getVertex(dest) : undefined;\n\n if (!srcVertex) {\n return undefined;\n }\n\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);\n }\n distMap.set(srcVertex, 0);\n preMap.set(srcVertex, undefined);\n\n const getMinOfNoSeen = () => {\n let min = Number.MAX_SAFE_INTEGER;\n let minV: VO | undefined = undefined;\n for (const [key, value] of distMap) {\n if (!seen.has(key)) {\n if (value < min) {\n min = value;\n minV = key;\n }\n }\n }\n return minV;\n };\n\n const getPaths = (minV: VO | undefined) => {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minV) minPath = reversed;\n paths.push(reversed);\n }\n }\n };\n\n for (let i = 1; i < vertexMap.size; i++) {\n const cur = getMinOfNoSeen();\n if (cur) {\n seen.add(cur);\n if (destVertex && destVertex === cur) {\n if (getMinDist) {\n minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;\n }\n if (genPaths) {\n getPaths(destVertex);\n }\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!seen.has(neighbor)) {\n const edge = this.getEdge(cur, neighbor);\n if (edge) {\n const curFromMap = distMap.get(cur);\n const neighborFromMap = distMap.get(neighbor);\n\n if (curFromMap !== undefined && neighborFromMap !== undefined) {\n if (edge.weight + curFromMap < neighborFromMap) {\n distMap.set(neighbor, edge.weight + curFromMap);\n preMap.set(neighbor, cur);\n }\n }\n }\n }\n }\n }\n }\n\n if (getMinDist)\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < minDist) {\n minDist = d;\n if (genPaths) minDest = v;\n }\n }\n });\n\n if (genPaths) getPaths(minDest);\n\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n\n dijkstra(\n src: VO | VertexKey,\n dest: VO | VertexKey | undefined = undefined,\n getMinDist: boolean = false,\n genPaths: boolean = false\n ): DijkstraResult<VO> | undefined {\n let minDist = Number.MAX_SAFE_INTEGER;\n let minDest: VO | undefined = undefined;\n let minPath: VO[] = [];\n const paths: VO[][] = [];\n const vertexMap = this._vertexMap;\n const distMap: Map<VO, number> = new Map();\n const seen: Set<VO> = new Set();\n const preMap: Map<VO, VO | undefined> = new Map();\n\n const srcVertex = this._getVertex(src);\n const destVertex = dest ? this._getVertex(dest) : undefined;\n\n if (!srcVertex) return undefined;\n\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);\n }\n\n const heap = new Heap<{ key: number; value: VO }>([], { comparator: (a, b) => a.key - b.key });\n heap.add({ key: 0, value: srcVertex });\n\n distMap.set(srcVertex, 0);\n preMap.set(srcVertex, undefined);\n\n const getPaths = (minV: VO | undefined) => {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minV) minPath = reversed;\n paths.push(reversed);\n }\n }\n };\n\n while (heap.size > 0) {\n const curHeapNode = heap.poll();\n const dist = curHeapNode?.key;\n const cur = curHeapNode?.value;\n if (dist !== undefined) {\n if (cur) {\n seen.add(cur);\n if (destVertex && destVertex === cur) {\n if (getMinDist) {\n minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;\n }\n if (genPaths) {\n getPaths(destVertex);\n }\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!seen.has(neighbor)) {\n const weight = this.getEdge(cur, neighbor)?.weight;\n if (typeof weight === 'number') {\n const distSrcToNeighbor = distMap.get(neighbor);\n if (distSrcToNeighbor !== undefined) {\n if (dist + weight < distSrcToNeighbor) {\n heap.add({ key: dist + weight, value: neighbor });\n preMap.set(neighbor, cur);\n distMap.set(neighbor, dist + weight);\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (getMinDist) {\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < minDist) {\n minDist = d;\n if (genPaths) minDest = v;\n }\n }\n });\n }\n\n if (genPaths) {\n getPaths(minDest);\n }\n\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n\n /**\n * Bellman-Ford single-source shortest paths with option to scan negative cycles.\n * @param src - Source vertex or key.\n * @param scanNegativeCycle - If `true`, also detect negative cycles.\n * @param getMin - If `true`, compute global minimum distance.\n * @param genPath - If `true`, generate path arrays via predecessor map.\n * @returns Result bag including distances, predecessors, and optional cycle flag.\n * @remarks Time O(V * E), Space O(V + E)\n */\n bellmanFord(src: VO | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) {\n if (getMin === undefined) getMin = false;\n if (genPath === undefined) genPath = false;\n\n const srcVertex = this._getVertex(src);\n const paths: VO[][] = [];\n const distMap: Map<VO, number> = new Map();\n const preMap: Map<VO, VO> = new Map();\n let min = Number.MAX_SAFE_INTEGER;\n let minPath: VO[] = [];\n\n let hasNegativeCycle: boolean | undefined;\n if (scanNegativeCycle) hasNegativeCycle = false;\n if (!srcVertex) return { hasNegativeCycle, distMap, preMap, paths, min, minPath };\n\n const vertexMap = this._vertexMap;\n const numOfVertices = vertexMap.size;\n const edgeMap = this.edgeSet();\n const numOfEdges = edgeMap.length;\n\n this._vertexMap.forEach(vertex => {\n distMap.set(vertex, Number.MAX_SAFE_INTEGER);\n });\n\n distMap.set(srcVertex, 0);\n\n for (let i = 1; i < numOfVertices; ++i) {\n for (let j = 0; j < numOfEdges; ++j) {\n const ends = this.getEndsOfEdge(edgeMap[j]);\n if (ends) {\n const [s, d] = ends;\n const weight = edgeMap[j].weight;\n const sWeight = distMap.get(s);\n const dWeight = distMap.get(d);\n if (sWeight !== undefined && dWeight !== undefined) {\n if (distMap.get(s) !== Number.MAX_SAFE_INTEGER && sWeight + weight < dWeight) {\n distMap.set(d, sWeight + weight);\n if (genPath) preMap.set(d, s);\n }\n }\n }\n }\n }\n\n let minDest: VO | undefined = undefined;\n if (getMin) {\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < min) {\n min = d;\n if (genPath) minDest = v;\n }\n }\n });\n }\n\n if (genPath) {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent !== undefined) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minDest) minPath = reversed;\n paths.push(reversed);\n }\n }\n }\n\n for (let j = 0; j < numOfEdges; ++j) {\n const ends = this.getEndsOfEdge(edgeMap[j]);\n if (ends) {\n const [s] = ends;\n const weight = edgeMap[j].weight;\n const sWeight = distMap.get(s);\n if (sWeight) {\n if (sWeight !== Number.MAX_SAFE_INTEGER && sWeight + weight < sWeight) hasNegativeCycle = true;\n }\n }\n }\n\n return { hasNegativeCycle, distMap, preMap, paths, min, minPath };\n }\n\n /**\n * Floyd–Warshall all-pairs shortest paths.\n * @returns `{ costs, predecessor }` matrices.\n * @remarks Time O(V^3), Space O(V^2)\n */\n floydWarshall(): { costs: number[][]; predecessor: (VO | undefined)[][] } {\n const idAndVertices = [...this._vertexMap];\n const n = idAndVertices.length;\n\n const costs: number[][] = [];\n const predecessor: (VO | undefined)[][] = [];\n\n for (let i = 0; i < n; i++) {\n costs[i] = [];\n predecessor[i] = [];\n for (let j = 0; j < n; j++) {\n predecessor[i][j] = undefined;\n }\n }\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Number.MAX_SAFE_INTEGER;\n }\n }\n\n for (let k = 0; k < n; k++) {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (costs[i][j] > costs[i][k] + costs[k][j]) {\n costs[i][j] = costs[i][k] + costs[k][j];\n predecessor[i][j] = idAndVertices[k][1];\n }\n }\n }\n }\n return { costs, predecessor };\n }\n\n /**\n * Enumerate simple cycles (may be expensive).\n * @param isInclude2Cycle - If `true`, include 2-cycles when graph semantics allow.\n * @returns Array of cycles (each as array of vertex keys).\n * @remarks Time exponential in worst-case, Space O(V + E)\n */\n getCycles(isInclude2Cycle: boolean = false): VertexKey[][] {\n const cycles: VertexKey[][] = [];\n const visited: Set<VO> = new Set();\n\n const dfs = (vertex: VO, currentPath: VertexKey[], visited: Set<VO>) => {\n if (visited.has(vertex)) {\n if (\n ((!isInclude2Cycle && currentPath.length > 2) || (isInclude2Cycle && currentPath.length >= 2)) &&\n currentPath[0] === vertex.key\n ) {\n cycles.push([...currentPath]);\n }\n return;\n }\n\n visited.add(vertex);\n currentPath.push(vertex.key);\n\n for (const neighbor of this.getNeighbors(vertex)) {\n if (neighbor) dfs(neighbor, currentPath, visited);\n }\n\n visited.delete(vertex);\n currentPath.pop();\n };\n\n for (const vertex of this.vertexMap.values()) {\n dfs(vertex, [], visited);\n }\n\n const uniqueCycles = new Map<string, VertexKey[]>();\n\n for (const cycle of cycles) {\n const sorted = [...cycle].sort().toString();\n\n if (uniqueCycles.has(sorted)) continue;\n else {\n uniqueCycles.set(sorted, cycle);\n }\n }\n\n /**\n * Map entries to an array via callback.\n * @param callback - `(key, value, index, self) => T`.\n * @param thisArg - Optional `this` for callback.\n * @returns Mapped results.\n * @remarks Time O(V), Space O(V)\n */\n return [...uniqueCycles].map(cycleString => cycleString[1]);\n }\n\n /**\n * Induced-subgraph filter: keep vertices where `predicate(key, value)` is true,\n * and only keep edges whose endpoints both survive.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n filter(predicate: EntryCallback<VertexKey, V | undefined, boolean>, thisArg?: any): this {\n const filtered: [VertexKey, V | undefined][] = [];\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, value, key, index, this)) {\n filtered.push([key, value]);\n }\n index++;\n }\n return this._createLike(filtered, this._snapshotOptions());\n }\n\n /**\n * Preserve the old behavior: return filtered entries as an array.\n * @remarks Time O(V), Space O(V)\n */\n filterEntries(\n predicate: EntryCallback<VertexKey, V | undefined, boolean>,\n thisArg?: any\n ): [VertexKey, V | undefined][] {\n const filtered: [VertexKey, V | undefined][] = [];\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, value, key, index, this)) {\n filtered.push([key, value]);\n }\n index++;\n }\n return filtered;\n }\n\n map<T>(callback: EntryCallback<VertexKey, V | undefined, T>, thisArg?: any): T[] {\n const mapped: T[] = [];\n let index = 0;\n for (const [key, value] of this) {\n mapped.push(callback.call(thisArg, value, key, index, this));\n index++;\n }\n return mapped;\n }\n\n /**\n * Create a deep clone of the graph with the same species.\n * @remarks Time O(V + E), Space O(V + E)\n */\n /**\n * Create a deep clone of the graph with the same species.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n clone(): this {\n return this._createLike(undefined, this._snapshotOptions());\n }\n\n // ===== Same-species factory & cloning helpers =====\n\n /**\n * Internal iterator over `[key, value]` entries in insertion order.\n * @returns Iterator of `[VertexKey, V | undefined]`.\n * @remarks Time O(V), Space O(1)\n */\n protected *_getIterator(): IterableIterator<[VertexKey, V | undefined]> {\n for (const vertex of this._vertexMap.values()) {\n yield [vertex.key, vertex.value];\n }\n }\n\n /**\n * Capture configuration needed to reproduce the current graph.\n * Currently the graph has no runtime options, so we return an empty object.\n */\n /**\n * Capture configuration needed to reproduce the current graph.\n * @returns Options bag (opaque to callers).\n * @remarks Time O(1), Space O(1)\n */\n protected _snapshotOptions(): Record<string, unknown> {\n return { graph: { ...this._options } };\n }\n\n /**\n * Create an empty graph instance of the same concrete species (Directed/Undirected/etc).\n * @remarks Time O(1), Space O(1)\n */\n /**\n * Create an empty graph instance of the same concrete species.\n * @param _options - Snapshot options from `_snapshotOptions()`.\n * @returns A new empty graph instance of `this` type.\n * @remarks Time O(1), Space O(1)\n */\n protected _createInstance(_options?: Partial<Record<string, unknown>>): this {\n const Ctor: any = (this as any).constructor;\n const instance: this = new Ctor();\n const graph = (_options as any)?.graph as GraphOptions<V> | undefined;\n if (graph) (instance as any)._options = { ...(instance as any)._options, ...graph };\n else (instance as any)._options = { ...(instance as any)._options, ...(this as any)._options };\n return instance;\n }\n\n /**\n * Create a same-species graph populated with the given entries.\n * Also preserves edges between kept vertices from the source graph.\n * @remarks Time O(V + E), Space O(V + E)\n */\n /**\n * Create a same-species graph populated with entries; preserves edges among kept vertices.\n * @param iter - Optional entries to seed the new graph.\n * @param options - Snapshot options.\n * @returns A new graph of `this` type.\n * @remarks Time O(V + E), Space O(V + E)\n */\n protected _createLike(iter?: Iterable<[VertexKey, V | undefined]>, options?: Partial<Record<string, unknown>>): this {\n const g = this._createInstance(options);\n // 1) Add vertices\n if (iter) {\n for (const [k, v] of iter) {\n (g as any).addVertex(k as VertexKey, v as V | undefined);\n }\n } else {\n for (const [k, v] of this) {\n (g as any).addVertex(k as VertexKey, v as V | undefined);\n }\n }\n // 2) Add edges whose endpoints exist in the new graph\n const edges = this.edgeSet();\n for (const e of edges as any[]) {\n const ends = this.getEndsOfEdge(e as any) as unknown as [any, any] | undefined;\n if (!ends) continue;\n const [va, vb] = ends;\n const ka = (va as any).key as VertexKey;\n const kb = (vb as any).key as VertexKey;\n const hasA = (g as any).hasVertex ? (g as any).hasVertex(ka) : false;\n const hasB = (g as any).hasVertex ? (g as any).hasVertex(kb) : false;\n if (hasA && hasB) {\n const w = (e as any).weight;\n const val = (e as any).value;\n const newEdge = (g as any).createEdge(ka, kb, w, val);\n (g as any)._addEdge(newEdge);\n }\n }\n return g;\n }\n\n /**\n * Internal hook to attach an edge into adjacency structures.\n * @param edge - Edge instance.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected abstract _addEdge(edge: EO): boolean;\n\n /**\n * Insert a pre-built vertex into the graph.\n * @param newVertex - Concrete vertex instance.\n * @returns `true` if inserted; `false` if key already exists.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addVertex(newVertex: VO): boolean {\n if (this.hasVertex(newVertex)) {\n return false;\n }\n this._vertexMap.set(newVertex.key, newVertex);\n return true;\n }\n\n /**\n * Resolve a vertex key or instance to the concrete vertex instance.\n * @param vertexOrKey - Vertex key or existing vertex.\n * @returns Vertex instance or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n protected _getVertex(vertexOrKey: VertexKey | VO): VO | undefined {\n const vertexKey = this._getVertexKey(vertexOrKey);\n return this._vertexMap.get(vertexKey) || undefined;\n }\n\n /**\n * Resolve a vertex key from a key or vertex instance.\n * @param vertexOrKey - Vertex key or existing vertex.\n * @returns The vertex key.\n * @remarks Time O(1), Space O(1)\n */\n protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey {\n return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { GraphOptions, TopologicalStatus, VertexKey } from '../../types';\nimport { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';\nimport { IGraph } from '../../interfaces';\nimport { arrayRemove } from '../../utils';\n\nexport class DirectedVertex<V = any> extends AbstractVertex<V> {\n constructor(key: VertexKey, value?: V) {\n super(key, value);\n }\n}\n\nexport class DirectedEdge<E = any> extends AbstractEdge<E> {\n src: VertexKey;\n dest: VertexKey;\n\n constructor(src: VertexKey, dest: VertexKey, weight?: number, value?: E) {\n super(weight, value);\n this.src = src;\n this.dest = dest;\n }\n}\n\n/**\n * Directed graph implementation.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (extends AbstractVertex<V>).\n * @template EO - Concrete edge class (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example\n * // basic DirectedGraph vertex and edge creation\n * // Create a simple directed graph\n * const graph = new DirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n *\n * // Verify vertices exist\n * console.log(graph.hasVertex('A')); // true;\n * console.log(graph.hasVertex('B')); // true;\n * console.log(graph.hasVertex('C')); // true;\n * console.log(graph.hasVertex('D')); // false;\n *\n * // Check vertex count\n * console.log(graph.size); // 3;\n * @example\n * // DirectedGraph edge operations\n * const graph = new DirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n *\n * // Add directed edges\n * graph.addEdge('A', 'B', 1);\n * graph.addEdge('B', 'C', 2);\n * graph.addEdge('A', 'C', 3);\n *\n * // Verify edges exist\n * console.log(graph.hasEdge('A', 'B')); // true;\n * console.log(graph.hasEdge('B', 'C')); // true;\n * console.log(graph.hasEdge('C', 'B')); // false; // Graph is directed\n *\n * // Get neighbors of A\n * const neighborsA = graph.getNeighbors('A');\n * console.log(neighborsA[0].key); // 'B';\n * console.log(neighborsA[1].key); // 'C';\n * @example\n * // DirectedGraph deleteEdge and vertex operations\n * const graph = new DirectedGraph<string>();\n *\n * // Build a small graph\n * graph.addVertex('X');\n * graph.addVertex('Y');\n * graph.addVertex('Z');\n * graph.addEdge('X', 'Y', 1);\n * graph.addEdge('Y', 'Z', 2);\n *\n * // Delete an edge\n * graph.deleteEdgeSrcToDest('X', 'Y');\n * console.log(graph.hasEdge('X', 'Y')); // false;\n *\n * // Edge in other direction should not exist\n * console.log(graph.hasEdge('Y', 'X')); // false;\n *\n * // Other edges should remain\n * console.log(graph.hasEdge('Y', 'Z')); // true;\n *\n * // Delete a vertex\n * graph.deleteVertex('Y');\n * console.log(graph.hasVertex('Y')); // false;\n * console.log(graph.size); // 2;\n * @example\n * // DirectedGraph topologicalSort for task scheduling\n * const graph = new DirectedGraph<string>();\n *\n * // Build a DAG (Directed Acyclic Graph) for task dependencies\n * graph.addVertex('Design');\n * graph.addVertex('Implement');\n * graph.addVertex('Test');\n * graph.addVertex('Deploy');\n *\n * // Add dependency edges\n * graph.addEdge('Design', 'Implement', 1); // Design must come before Implement\n * graph.addEdge('Implement', 'Test', 1); // Implement must come before Test\n * graph.addEdge('Test', 'Deploy', 1); // Test must come before Deploy\n *\n * // Topological sort gives valid execution order\n * const executionOrder = graph.topologicalSort();\n * console.log(executionOrder); // defined;\n * console.log(executionOrder); // ['Design', 'Implement', 'Test', 'Deploy'];\n *\n * // All vertices should be included\n * console.log(executionOrder?.length); // 4;\n * @example\n * // DirectedGraph dijkstra shortest path for network routing\n * // Build a weighted directed graph representing network nodes and costs\n * const network = new DirectedGraph<string>();\n *\n * // Add network nodes\n * network.addVertex('Router-A');\n * network.addVertex('Router-B');\n * network.addVertex('Router-C');\n * network.addVertex('Router-D');\n * network.addVertex('Router-E');\n *\n * // Add weighted edges (network latency costs)\n * network.addEdge('Router-A', 'Router-B', 5);\n * network.addEdge('Router-A', 'Router-C', 10);\n * network.addEdge('Router-B', 'Router-D', 3);\n * network.addEdge('Router-C', 'Router-D', 2);\n * network.addEdge('Router-D', 'Router-E', 4);\n * network.addEdge('Router-B', 'Router-E', 12);\n *\n * // Find shortest path from Router-A to Router-E\n * const { minDist, minPath } = network.dijkstra('Router-A', 'Router-E', true, true) || {\n * minDist: undefined,\n * minPath: undefined\n * };\n *\n * // Verify shortest path is found\n * console.log(minDist); // defined;\n * console.log(minPath); // defined;\n *\n * // Shortest path should be A -> B -> D -> E with cost 5+3+4=12\n * // Or A -> C -> D -> E with cost 10+2+4=16\n * // So the minimum is 12\n * console.log(minDist); // <= 16;\n *\n * // Verify path is valid (includes start and end)\n * console.log(minPath?.[0].key); // 'Router-A';\n * console.log(minPath?.[minPath.length - 1].key); // 'Router-E';\n */\nexport class DirectedGraph<\n V = any,\n E = any,\n VO extends DirectedVertex<V> = DirectedVertex<V>,\n EO extends DirectedEdge<E> = DirectedEdge<E>\n>\n extends AbstractGraph<V, E, VO, EO>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct a directed graph with runtime defaults.\n * @param options - `GraphOptions<V>` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<GraphOptions<V>>) {\n super(options);\n }\n\n protected _outEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();\n\n get outEdgeMap(): Map<VO, EO[]> {\n return this._outEdgeMap;\n }\n\n set outEdgeMap(v: Map<VO, EO[]>) {\n this._outEdgeMap = v;\n }\n\n protected _inEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();\n\n get inEdgeMap(): Map<VO, EO[]> {\n return this._inEdgeMap;\n }\n\n set inEdgeMap(v: Map<VO, EO[]>) {\n this._inEdgeMap = v;\n }\n\n /**\n * Construct a directed graph from keys with value initializer `v => v`.\n * @template K - Vertex key type.\n * @param keys - Iterable of vertex keys.\n * @returns DirectedGraph with all keys added.\n * @remarks Time O(V), Space O(V)\n */\n static fromKeys<K extends VertexKey>(keys: Iterable<K>): DirectedGraph<K, any, DirectedVertex<K>, DirectedEdge<any>> {\n const g: DirectedGraph<K, any, DirectedVertex<K>, DirectedEdge<any>> = new DirectedGraph<K, any>({\n vertexValueInitializer: (k: VertexKey) => k as K\n });\n for (const k of keys) g.addVertex(k);\n return g;\n }\n\n /**\n * Construct a directed graph from `[key, value]` entries.\n * @template V - Vertex value type.\n * @param entries - Iterable of `[key, value]` pairs.\n * @returns DirectedGraph with all vertices added.\n * @remarks Time O(V), Space O(V)\n */\n static fromEntries<V>(\n entries: Iterable<[VertexKey, V]>\n ): DirectedGraph<V, any, DirectedVertex<V>, DirectedEdge<any>> {\n const g: DirectedGraph<V, any, DirectedVertex<V>, DirectedEdge<any>> = new DirectedGraph<V, any>();\n for (const [k, v] of entries) g.addVertex(k, v);\n return g;\n }\n\n /**\n * Create a directed vertex instance. Does not insert into the graph.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n createVertex(key: VertexKey, value?: VO['value']): VO {\n return new DirectedVertex(key, value) as VO;\n }\n\n /**\n * Create a directed edge instance. Does not insert into the graph.\n * @param src - Source vertex key.\n * @param dest - Destination vertex key.\n * @param weight - Edge weight; defaults to `defaultEdgeWeight`.\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n createEdge(src: VertexKey, dest: VertexKey, weight?: number, value?: E): EO {\n return new DirectedEdge(src, dest, weight ?? this.options.defaultEdgeWeight ?? 1, value) as EO;\n }\n\n /**\n * Get the unique edge from `src` to `dest`, if present.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n getEdge(srcOrKey: VO | VertexKey | undefined, destOrKey: VO | VertexKey | undefined): EO | undefined {\n let edgeMap: EO[] = [];\n\n if (srcOrKey !== undefined && destOrKey !== undefined) {\n const src: VO | undefined = this._getVertex(srcOrKey);\n const dest: VO | undefined = this._getVertex(destOrKey);\n\n if (src && dest) {\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges) {\n edgeMap = srcOutEdges.filter(edge => edge.dest === dest.key);\n }\n }\n }\n\n return edgeMap[0] || undefined;\n }\n\n /**\n * Delete edge `src -> dest` if present.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdgeSrcToDest(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined {\n const src: VO | undefined = this._getVertex(srcOrKey);\n const dest: VO | undefined = this._getVertex(destOrKey);\n let removed: EO | undefined = undefined;\n if (!src || !dest) {\n return undefined;\n }\n\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges) {\n arrayRemove<EO>(srcOutEdges, (edge: EO) => edge.dest === dest.key);\n }\n\n const destInEdges = this._inEdgeMap.get(dest);\n if (destInEdges) {\n removed = arrayRemove<EO>(destInEdges, (edge: EO) => edge.src === src.key)[0] || undefined;\n }\n return removed;\n }\n\n /**\n * Delete an edge by instance or by `(srcKey, destKey)`.\n * @param edgeOrSrcVertexKey - Edge instance or source vertex/key.\n * @param destVertexKey - Optional destination vertex/key when deleting by pair.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdge(edgeOrSrcVertexKey: EO | VertexKey, destVertexKey?: VertexKey): EO | undefined {\n let removed: EO | undefined = undefined;\n let src: VO | undefined, dest: VO | undefined;\n if (this.isVertexKey(edgeOrSrcVertexKey)) {\n if (this.isVertexKey(destVertexKey)) {\n src = this._getVertex(edgeOrSrcVertexKey);\n dest = this._getVertex(destVertexKey);\n } else {\n return;\n }\n } else {\n src = this._getVertex(edgeOrSrcVertexKey.src);\n dest = this._getVertex(edgeOrSrcVertexKey.dest);\n }\n\n if (src && dest) {\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges && srcOutEdges.length > 0) {\n arrayRemove(srcOutEdges, (edge: EO) => edge.src === src!.key && edge.dest === dest?.key);\n }\n\n const destInEdges = this._inEdgeMap.get(dest);\n if (destInEdges && destInEdges.length > 0) {\n removed = arrayRemove(destInEdges, (edge: EO) => edge.src === src!.key && edge.dest === dest!.key)[0];\n }\n }\n\n return removed;\n }\n\n deleteVertex(vertexOrKey: VO | VertexKey): boolean {\n let vertexKey: VertexKey;\n let vertex: VO | undefined;\n if (this.isVertexKey(vertexOrKey)) {\n vertex = this.getVertex(vertexOrKey);\n vertexKey = vertexOrKey;\n } else {\n vertex = vertexOrKey;\n vertexKey = this._getVertexKey(vertexOrKey);\n }\n\n if (vertex) {\n /**\n * One-step neighbors following outgoing edges.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n this.deleteEdgeSrcToDest(vertex, neighbor);\n }\n this._outEdgeMap.delete(vertex);\n this._inEdgeMap.delete(vertex);\n }\n\n return this._vertexMap.delete(vertexKey);\n }\n\n deleteEdgesBetween(v1: VertexKey | VO, v2: VertexKey | VO): EO[] {\n const removed: EO[] = [];\n\n if (v1 && v2) {\n const v1ToV2 = this.deleteEdgeSrcToDest(v1, v2);\n const v2ToV1 = this.deleteEdgeSrcToDest(v2, v1);\n\n if (v1ToV2) removed.push(v1ToV2);\n if (v2ToV1) removed.push(v2ToV1);\n }\n\n return removed;\n }\n\n /**\n * Incoming edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incoming edges.\n * @remarks Time O(deg_in), Space O(deg_in)\n */\n incomingEdgesOf(vertexOrKey: VO | VertexKey): EO[] {\n const target = this._getVertex(vertexOrKey);\n if (target) {\n return this.inEdgeMap.get(target) || [];\n }\n return [];\n }\n\n /**\n * Outgoing edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of outgoing edges.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n outgoingEdgesOf(vertexOrKey: VO | VertexKey): EO[] {\n const target = this._getVertex(vertexOrKey);\n if (target) {\n return this._outEdgeMap.get(target) || [];\n }\n return [];\n }\n\n /**\n * Degree (in + out) of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n degreeOf(vertexOrKey: VertexKey | VO): number {\n /**\n * In-degree of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n /**\n * Out-degree of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n return this.outDegreeOf(vertexOrKey) + this.inDegreeOf(vertexOrKey);\n }\n\n inDegreeOf(vertexOrKey: VertexKey | VO): number {\n return this.incomingEdgesOf(vertexOrKey).length;\n }\n\n outDegreeOf(vertexOrKey: VertexKey | VO): number {\n return this.outgoingEdgesOf(vertexOrKey).length;\n }\n\n /**\n * All incident edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg_in + deg_out), Space O(deg_in + deg_out)\n */\n edgesOf(vertexOrKey: VertexKey | VO): EO[] {\n return [...this.outgoingEdgesOf(vertexOrKey), ...this.incomingEdgesOf(vertexOrKey)];\n }\n\n getEdgeSrc(e: EO): VO | undefined {\n return this._getVertex(e.src);\n }\n\n getEdgeDest(e: EO): VO | undefined {\n return this._getVertex(e.dest);\n }\n\n /**\n * Direct children reachable by one outgoing edge.\n * @param vertex - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n getDestinations(vertex: VO | VertexKey | undefined): VO[] {\n if (vertex === undefined) {\n return [];\n }\n const destinations: VO[] = [];\n const outgoingEdges = this.outgoingEdgesOf(vertex);\n for (const outEdge of outgoingEdges) {\n const child = this.getEdgeDest(outEdge);\n if (child) {\n destinations.push(child);\n }\n }\n return destinations;\n }\n\n /**\n * Topological sort if DAG; returns `undefined` if a cycle exists.\n * @param propertyName - `'key'` to map to keys; `'vertex'` to keep instances.\n * @returns Array of keys/vertices, or `undefined` when cycle is found.\n * @remarks Time O(V + E), Space O(V)\n */\n topologicalSort(propertyName?: 'vertex' | 'key'): Array<VO | VertexKey> | undefined {\n propertyName = propertyName ?? 'key';\n\n const statusMap: Map<VO | VertexKey, TopologicalStatus> = new Map<VO | VertexKey, TopologicalStatus>();\n for (const entry of this.vertexMap) {\n statusMap.set(entry[1], 0);\n }\n\n let sorted: (VO | VertexKey)[] = [];\n let hasCycle = false;\n const dfs = (cur: VO | VertexKey) => {\n statusMap.set(cur, 1);\n const children = this.getDestinations(cur);\n for (const child of children) {\n const childStatus = statusMap.get(child);\n if (childStatus === 0) {\n dfs(child);\n } else if (childStatus === 1) {\n hasCycle = true;\n }\n }\n statusMap.set(cur, 2);\n sorted.push(cur);\n };\n\n for (const entry of this.vertexMap) {\n if (statusMap.get(entry[1]) === 0) {\n dfs(entry[1]);\n }\n }\n\n if (hasCycle) return undefined;\n\n if (propertyName === 'key') sorted = sorted.map(vertex => (vertex instanceof DirectedVertex ? vertex.key : vertex));\n return sorted.reverse();\n }\n\n edgeSet(): EO[] {\n let edgeMap: EO[] = [];\n this._outEdgeMap.forEach(outEdges => {\n edgeMap = [...edgeMap, ...outEdges];\n });\n return edgeMap;\n }\n\n getNeighbors(vertexOrKey: VO | VertexKey): VO[] {\n const neighbors: VO[] = [];\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n const outEdges = this.outgoingEdgesOf(vertex);\n for (const outEdge of outEdges) {\n const neighbor = this._getVertex(outEdge.dest);\n\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n }\n return neighbors;\n }\n\n /**\n * Resolve an edge's `[src, dest]` endpoints to vertex instances.\n * @param edge - Edge instance.\n * @returns `[src, dest]` or `undefined` if either endpoint is missing.\n * @remarks Time O(1), Space O(1)\n */\n getEndsOfEdge(edge: EO): [VO, VO] | undefined {\n if (!this.hasEdge(edge.src, edge.dest)) {\n return undefined;\n }\n const v1 = this._getVertex(edge.src);\n const v2 = this._getVertex(edge.dest);\n if (v1 && v2) {\n return [v1, v2];\n } else {\n return undefined;\n }\n }\n\n /**\n * Whether the graph has no vertices and no edges.\n * @remarks Time O(1), Space O(1)\n */\n isEmpty(): boolean {\n return this.vertexMap.size === 0 && this.inEdgeMap.size === 0 && this.outEdgeMap.size === 0;\n }\n\n /**\n * Remove all vertices and edges.\n * @remarks Time O(V + E), Space O(1)\n */\n clear() {\n this._vertexMap = new Map<VertexKey, VO>();\n this._inEdgeMap = new Map<VO, EO[]>();\n this._outEdgeMap = new Map<VO, EO[]>();\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Tarjan's algorithm for strongly connected components.\n * @returns `{ dfnMap, lowMap, SCCs }`.\n * @remarks Time O(V + E), Space O(V + E)\n */\n tarjan(): { dfnMap: Map<VO, number>; lowMap: Map<VO, number>; SCCs: Map<number, VO[]> } {\n const dfnMap = new Map<VO, number>();\n const lowMap = new Map<VO, number>();\n const SCCs = new Map<number, VO[]>();\n\n let time = 0;\n\n const stack: VO[] = [];\n const inStack: Set<VO> = new Set();\n\n const dfs = (vertex: VO) => {\n dfnMap.set(vertex, time);\n lowMap.set(vertex, time);\n time++;\n\n stack.push(vertex);\n inStack.add(vertex);\n\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n if (!dfnMap.has(neighbor)) {\n dfs(neighbor);\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, lowMap.get(neighbor)!));\n } else if (inStack.has(neighbor)) {\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, dfnMap.get(neighbor)!));\n }\n }\n\n if (dfnMap.get(vertex) === lowMap.get(vertex)) {\n const SCC: VO[] = [];\n let poppedVertex: VO | undefined;\n\n do {\n poppedVertex = stack.pop();\n inStack.delete(poppedVertex!);\n SCC.push(poppedVertex!);\n } while (poppedVertex !== vertex);\n\n SCCs.set(SCCs.size, SCC);\n }\n };\n\n for (const vertex of this.vertexMap.values()) {\n if (!dfnMap.has(vertex)) {\n dfs(vertex);\n }\n }\n\n return { dfnMap, lowMap, SCCs };\n }\n\n /**\n * DFN index map computed by `tarjan()`.\n * @returns Map from vertex to DFN index.\n * @remarks Time O(V), Space O(V)\n */\n getDFNMap(): Map<VO, number> {\n return this.tarjan().dfnMap;\n }\n\n /**\n * LOW link map computed by `tarjan()`.\n * @returns Map from vertex to LOW value.\n * @remarks Time O(V), Space O(V)\n */\n getLowMap(): Map<VO, number> {\n return this.tarjan().lowMap;\n }\n\n /**\n * Strongly connected components computed by `tarjan()`.\n * @returns Map from SCC id to vertices.\n * @remarks Time O(#SCC + V), Space O(V)\n */\n getSCCs(): Map<number, VO[]> {\n return this.tarjan().SCCs;\n }\n\n /**\n * Internal hook to attach a directed edge into adjacency maps.\n * @param edge - Edge instance.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addEdge(edge: EO): boolean {\n if (!(this.hasVertex(edge.src) && this.hasVertex(edge.dest))) {\n return false;\n }\n\n const srcVertex = this._getVertex(edge.src);\n const destVertex = this._getVertex(edge.dest);\n\n if (srcVertex && destVertex) {\n const srcOutEdges = this._outEdgeMap.get(srcVertex);\n if (srcOutEdges) {\n srcOutEdges.push(edge);\n } else {\n this._outEdgeMap.set(srcVertex, [edge]);\n }\n\n const destInEdges = this._inEdgeMap.get(destVertex);\n if (destInEdges) {\n destInEdges.push(edge);\n } else {\n this._inEdgeMap.set(destVertex, [edge]);\n }\n return true;\n } else {\n return false;\n }\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { GraphOptions, VertexKey } from '../../types';\nimport { IGraph } from '../../interfaces';\nimport { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';\nimport { arrayRemove } from '../../utils';\n\nexport class UndirectedVertex<V = any> extends AbstractVertex<V> {\n constructor(key: VertexKey, value?: V) {\n super(key, value);\n }\n}\n\nexport class UndirectedEdge<E = number> extends AbstractEdge<E> {\n endpoints: [VertexKey, VertexKey];\n\n constructor(v1: VertexKey, v2: VertexKey, weight?: number, value?: E) {\n super(weight, value);\n this.endpoints = [v1, v2];\n }\n}\n\n/**\n * Undirected graph implementation.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (extends AbstractVertex<V>).\n * @template EO - Concrete edge class (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example\n * // basic UndirectedGraph vertex and edge creation\n * // Create a simple undirected graph\n * const graph = new UndirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n * graph.addVertex('D');\n *\n * // Verify vertices exist\n * console.log(graph.hasVertex('A')); // true;\n * console.log(graph.hasVertex('B')); // true;\n * console.log(graph.hasVertex('E')); // false;\n *\n * // Check vertex count\n * console.log(graph.size); // 4;\n * @example\n * // UndirectedGraph edge operations (bidirectional)\n * const graph = new UndirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n *\n * // Add undirected edges (both directions automatically)\n * graph.addEdge('A', 'B', 1);\n * graph.addEdge('B', 'C', 2);\n * graph.addEdge('A', 'C', 3);\n *\n * // Verify edges exist in both directions\n * console.log(graph.hasEdge('A', 'B')); // true;\n * console.log(graph.hasEdge('B', 'A')); // true; // Bidirectional!\n *\n * console.log(graph.hasEdge('C', 'B')); // true;\n * console.log(graph.hasEdge('B', 'C')); // true; // Bidirectional!\n *\n * // Get neighbors of A\n * const neighborsA = graph.getNeighbors('A');\n * console.log(neighborsA[0].key); // 'B';\n * console.log(neighborsA[1].key); // 'C';\n * @example\n * // UndirectedGraph deleteEdge and vertex operations\n * const graph = new UndirectedGraph<string>();\n *\n * // Build a simple undirected graph\n * graph.addVertex('X');\n * graph.addVertex('Y');\n * graph.addVertex('Z');\n * graph.addEdge('X', 'Y', 1);\n * graph.addEdge('Y', 'Z', 2);\n * graph.addEdge('X', 'Z', 3);\n *\n * // Delete an edge\n * graph.deleteEdge('X', 'Y');\n * console.log(graph.hasEdge('X', 'Y')); // false;\n *\n * // Bidirectional deletion confirmed\n * console.log(graph.hasEdge('Y', 'X')); // false;\n *\n * // Other edges should remain\n * console.log(graph.hasEdge('Y', 'Z')); // true;\n * console.log(graph.hasEdge('Z', 'Y')); // true;\n *\n * // Delete a vertex\n * graph.deleteVertex('Y');\n * console.log(graph.hasVertex('Y')); // false;\n * console.log(graph.size); // 2;\n * @example\n * // UndirectedGraph connectivity and neighbors\n * const graph = new UndirectedGraph<string>();\n *\n * // Build a friendship network\n * const people = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'];\n * for (const person of people) {\n * graph.addVertex(person);\n * }\n *\n * // Add friendships (undirected edges)\n * graph.addEdge('Alice', 'Bob', 1);\n * graph.addEdge('Alice', 'Charlie', 1);\n * graph.addEdge('Bob', 'Diana', 1);\n * graph.addEdge('Charlie', 'Eve', 1);\n * graph.addEdge('Diana', 'Eve', 1);\n *\n * // Get friends of each person\n * const aliceFriends = graph.getNeighbors('Alice');\n * console.log(aliceFriends[0].key); // 'Bob';\n * console.log(aliceFriends[1].key); // 'Charlie';\n * console.log(aliceFriends.length); // 2;\n *\n * const dianaFriends = graph.getNeighbors('Diana');\n * console.log(dianaFriends[0].key); // 'Bob';\n * console.log(dianaFriends[1].key); // 'Eve';\n * console.log(dianaFriends.length); // 2;\n *\n * // Verify bidirectional friendship\n * const bobFriends = graph.getNeighbors('Bob');\n * console.log(bobFriends[0].key); // 'Alice'; // Alice -> Bob -> Alice ✓\n * console.log(bobFriends[1].key); // 'Diana';\n * @example\n * // UndirectedGraph for social network connectivity analysis\n * interface Person {\n * id: number;\n * name: string;\n * location: string;\n * }\n *\n * // UndirectedGraph is perfect for modeling symmetric relationships\n * // (friendships, collaborations, partnerships)\n * const socialNetwork = new UndirectedGraph<number, Person>();\n *\n * // Add people as vertices\n * const people: [number, Person][] = [\n * [1, { id: 1, name: 'Alice', location: 'New York' }],\n * [2, { id: 2, name: 'Bob', location: 'San Francisco' }],\n * [3, { id: 3, name: 'Charlie', location: 'Boston' }],\n * [4, { id: 4, name: 'Diana', location: 'New York' }],\n * [5, { id: 5, name: 'Eve', location: 'Seattle' }]\n * ];\n *\n * for (const [id] of people) {\n * socialNetwork.addVertex(id);\n * }\n *\n * // Add friendships (automatically bidirectional)\n * socialNetwork.addEdge(1, 2, 1); // Alice <-> Bob\n * socialNetwork.addEdge(1, 3, 1); // Alice <-> Charlie\n * socialNetwork.addEdge(2, 4, 1); // Bob <-> Diana\n * socialNetwork.addEdge(3, 5, 1); // Charlie <-> Eve\n * socialNetwork.addEdge(4, 5, 1); // Diana <-> Eve\n *\n * console.log(socialNetwork.size); // 5;\n *\n * // Find direct connections for Alice\n * const aliceConnections = socialNetwork.getNeighbors(1);\n * console.log(aliceConnections[0].key); // 2;\n * console.log(aliceConnections[1].key); // 3;\n * console.log(aliceConnections.length); // 2;\n *\n * // Verify bidirectional connections\n * console.log(socialNetwork.hasEdge(1, 2)); // true;\n * console.log(socialNetwork.hasEdge(2, 1)); // true; // Friendship works both ways!\n *\n * // Remove a person from network\n * socialNetwork.deleteVertex(2); // Bob leaves\n * console.log(socialNetwork.hasVertex(2)); // false;\n * console.log(socialNetwork.size); // 4;\n *\n * // Alice loses Bob as a friend\n * const updatedAliceConnections = socialNetwork.getNeighbors(1);\n * console.log(updatedAliceConnections[0].key); // 3;\n * console.log(updatedAliceConnections[1]); // undefined;\n *\n * // Diana loses Bob as a friend\n * const dianaConnections = socialNetwork.getNeighbors(4);\n * console.log(dianaConnections[0].key); // 5;\n * console.log(dianaConnections[1]); // undefined;\n */\nexport class UndirectedGraph<\n V = any,\n E = any,\n VO extends UndirectedVertex<V> = UndirectedVertex<V>,\n EO extends UndirectedEdge<E> = UndirectedEdge<E>\n>\n extends AbstractGraph<V, E, VO, EO>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct an undirected graph with runtime defaults.\n * @param options - `GraphOptions<V>` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<GraphOptions<V>>) {\n super(options);\n this._edgeMap = new Map<VO, EO[]>();\n }\n\n protected _edgeMap: Map<VO, EO[]>;\n\n get edgeMap(): Map<VO, EO[]> {\n return this._edgeMap;\n }\n\n set edgeMap(v: Map<VO, EO[]>) {\n this._edgeMap = v;\n }\n\n /**\n * Construct an undirected graph from keys with value initializer `v => v`.\n * @template K - Vertex key type.\n * @param keys - Iterable of vertex keys.\n * @returns UndirectedGraph with all keys added.\n * @remarks Time O(V), Space O(V)\n */\n static fromKeys<K extends VertexKey>(\n keys: Iterable<K>\n ): UndirectedGraph<K, any, UndirectedVertex<K>, UndirectedEdge<any>> {\n const g: UndirectedGraph<K, any, UndirectedVertex<K>, UndirectedEdge<any>> = new UndirectedGraph<K, any>({\n vertexValueInitializer: (k: VertexKey) => k as K\n });\n for (const k of keys) g.addVertex(k);\n return g;\n }\n\n /**\n * Construct an undirected graph from `[key, value]` entries.\n * @template V - Vertex value type.\n * @param entries - Iterable of `[key, value]` pairs.\n * @returns UndirectedGraph with all vertices added.\n * @remarks Time O(V), Space O(V)\n */\n static fromEntries<V>(\n entries: Iterable<[VertexKey, V]>\n ): UndirectedGraph<V, any, UndirectedVertex<V>, UndirectedEdge<any>> {\n const g: UndirectedGraph<V, any, UndirectedVertex<V>, UndirectedEdge<any>> = new UndirectedGraph<V, any>();\n for (const [k, v] of entries) g.addVertex(k, v);\n return g;\n }\n\n /**\n * Create an undirected vertex instance. Does not insert into the graph.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n createVertex(key: VertexKey, value?: VO['value']): VO {\n return new UndirectedVertex(key, value) as VO;\n }\n\n /**\n * Create an undirected edge instance. Does not insert into the graph.\n * @param v1 - One endpoint key.\n * @param v2 - The other endpoint key.\n * @param weight - Edge weight; defaults to `defaultEdgeWeight`.\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n override createEdge(v1: VertexKey, v2: VertexKey, weight?: number, value?: EO['value']): EO {\n return new UndirectedEdge(v1, v2, weight ?? this.options.defaultEdgeWeight ?? 1, value) as EO;\n }\n\n /**\n * Get an undirected edge between two vertices, if present.\n * @param v1 - One vertex or key.\n * @param v2 - The other vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n getEdge(v1: VO | VertexKey | undefined, v2: VO | VertexKey | undefined): EO | undefined {\n let edgeMap: EO[] | undefined = [];\n\n if (v1 !== undefined && v2 !== undefined) {\n const vertex1: VO | undefined = this._getVertex(v1);\n const vertex2: VO | undefined = this._getVertex(v2);\n\n if (vertex1 && vertex2) {\n edgeMap = this._edgeMap.get(vertex1)?.filter(e => e.endpoints.includes(vertex2.key));\n }\n }\n\n return edgeMap ? edgeMap[0] || undefined : undefined;\n }\n\n /**\n * Delete a single undirected edge between two vertices.\n * @param v1 - One vertex or key.\n * @param v2 - The other vertex or key.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdgeBetween(v1: VO | VertexKey, v2: VO | VertexKey): EO | undefined {\n const vertex1: VO | undefined = this._getVertex(v1);\n const vertex2: VO | undefined = this._getVertex(v2);\n\n if (!vertex1 || !vertex2) {\n return undefined;\n }\n\n const v1Edges = this._edgeMap.get(vertex1);\n let removed: EO | undefined = undefined;\n if (v1Edges) {\n removed = arrayRemove<EO>(v1Edges, (e: EO) => e.endpoints.includes(vertex2.key))[0] || undefined;\n }\n const v2Edges = this._edgeMap.get(vertex2);\n if (v2Edges) {\n arrayRemove<EO>(v2Edges, (e: EO) => e.endpoints.includes(vertex1.key));\n }\n return removed;\n }\n\n /**\n * Delete an edge by instance or by a pair of keys.\n * @param edgeOrOneSideVertexKey - Edge instance or one endpoint vertex/key.\n * @param otherSideVertexKey - Required second endpoint when deleting by pair.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdge(edgeOrOneSideVertexKey: EO | VertexKey, otherSideVertexKey?: VertexKey): EO | undefined {\n let oneSide: VO | undefined, otherSide: VO | undefined;\n if (this.isVertexKey(edgeOrOneSideVertexKey)) {\n if (this.isVertexKey(otherSideVertexKey)) {\n oneSide = this._getVertex(edgeOrOneSideVertexKey);\n otherSide = this._getVertex(otherSideVertexKey);\n } else {\n return;\n }\n } else {\n oneSide = this._getVertex(edgeOrOneSideVertexKey.endpoints[0]);\n otherSide = this._getVertex(edgeOrOneSideVertexKey.endpoints[1]);\n }\n\n if (oneSide && otherSide) {\n return this.deleteEdgeBetween(oneSide, otherSide);\n } else {\n return;\n }\n }\n\n /**\n * Delete a vertex and remove it from all neighbor lists.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if removed; otherwise `false`.\n * @remarks Time O(deg), Space O(1)\n */\n deleteVertex(vertexOrKey: VO | VertexKey): boolean {\n let vertexKey: VertexKey;\n let vertex: VO | undefined;\n if (this.isVertexKey(vertexOrKey)) {\n vertex = this.getVertex(vertexOrKey);\n vertexKey = vertexOrKey;\n } else {\n vertex = vertexOrKey;\n vertexKey = this._getVertexKey(vertexOrKey);\n }\n\n /**\n * All neighbors connected via undirected edges.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg), Space O(deg)\n */\n const neighbors = this.getNeighbors(vertexOrKey);\n\n if (vertex) {\n neighbors.forEach(neighbor => {\n const neighborEdges = this._edgeMap.get(neighbor);\n if (neighborEdges) {\n const restEdges = neighborEdges.filter(edge => {\n return !edge.endpoints.includes(vertexKey);\n });\n this._edgeMap.set(neighbor, restEdges);\n }\n });\n this._edgeMap.delete(vertex);\n }\n\n return this._vertexMap.delete(vertexKey);\n }\n\n /**\n * Degree of a vertex (# of incident undirected edges).\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n degreeOf(vertexOrKey: VertexKey | VO): number {\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n return this._edgeMap.get(vertex)?.length || 0;\n } else {\n return 0;\n }\n }\n\n /**\n * Incident undirected edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg), Space O(deg)\n */\n edgesOf(vertexOrKey: VertexKey | VO): EO[] {\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n return this._edgeMap.get(vertex) || [];\n } else {\n return [];\n }\n }\n\n /**\n * Unique set of undirected edges across endpoints.\n * @returns Array of edges.\n * @remarks Time O(E), Space O(E)\n */\n edgeSet(): EO[] {\n const edgeSet: Set<EO> = new Set();\n this._edgeMap.forEach(edgeMap => {\n edgeMap.forEach(edge => {\n edgeSet.add(edge);\n });\n });\n return [...edgeSet];\n }\n\n getNeighbors(vertexOrKey: VO | VertexKey): VO[] {\n const neighbors: VO[] = [];\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n const neighborEdges = this.edgesOf(vertex);\n for (const edge of neighborEdges) {\n const neighbor = this._getVertex(edge.endpoints.filter(e => e !== vertex.key)[0]);\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n }\n return neighbors;\n }\n\n /**\n * Resolve an edge's two endpoints to vertex instances.\n * @param edge - Edge instance.\n * @returns `[v1, v2]` or `undefined` if either endpoint is missing.\n * @remarks Time O(1), Space O(1)\n */\n getEndsOfEdge(edge: EO): [VO, VO] | undefined {\n if (!this.hasEdge(edge.endpoints[0], edge.endpoints[1])) {\n return undefined;\n }\n const v1 = this._getVertex(edge.endpoints[0]);\n const v2 = this._getVertex(edge.endpoints[1]);\n if (v1 && v2) {\n return [v1, v2];\n } else {\n return undefined;\n }\n }\n\n /**\n * Whether the graph has no vertices and no edges.\n * @remarks Time O(1), Space O(1)\n */\n isEmpty(): boolean {\n return this.vertexMap.size === 0 && this.edgeMap.size === 0;\n }\n\n /**\n * Remove all vertices and edges.\n * @remarks Time O(V + E), Space O(1)\n */\n clear() {\n this._vertexMap = new Map<VertexKey, VO>();\n this._edgeMap = new Map<VO, EO[]>();\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Tarjan-based bridge and articulation point detection.\n * @returns `{ dfnMap, lowMap, bridges, cutVertices }`.\n * @remarks Time O(V + E), Space O(V + E)\n */\n tarjan(): { dfnMap: Map<VO, number>; lowMap: Map<VO, number>; bridges: EO[]; cutVertices: VO[] } {\n const dfnMap = new Map<VO, number>();\n const lowMap = new Map<VO, number>();\n const bridges: EO[] = [];\n const cutVertices: VO[] = [];\n\n let time = 0;\n\n const dfs = (vertex: VO, parent: VO | undefined) => {\n dfnMap.set(vertex, time);\n lowMap.set(vertex, time);\n time++;\n\n const neighbors = this.getNeighbors(vertex);\n let childCount = 0;\n\n for (const neighbor of neighbors) {\n if (!dfnMap.has(neighbor)) {\n childCount++;\n dfs(neighbor, vertex);\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, lowMap.get(neighbor)!));\n\n if (lowMap.get(neighbor)! > dfnMap.get(vertex)!) {\n // Found a bridge\n const edge = this.getEdge(vertex, neighbor);\n if (edge) {\n bridges.push(edge);\n }\n }\n\n if (parent !== undefined && lowMap.get(neighbor)! >= dfnMap.get(vertex)!) {\n // Found an articulation point\n cutVertices.push(vertex);\n }\n } else if (neighbor !== parent) {\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, dfnMap.get(neighbor)!));\n }\n }\n\n if (parent === undefined && childCount > 1) {\n // Special case for root in DFS tree\n cutVertices.push(vertex);\n }\n };\n\n for (const vertex of this.vertexMap.values()) {\n if (!dfnMap.has(vertex)) {\n dfs(vertex, undefined);\n }\n }\n\n return {\n dfnMap,\n lowMap,\n bridges,\n cutVertices\n };\n }\n\n /**\n * Get bridges discovered by `tarjan()`.\n * @returns Array of edges that are bridges.\n * @remarks Time O(B), Space O(1)\n */\n getBridges() {\n return this.tarjan().bridges;\n }\n\n /**\n * Get articulation points discovered by `tarjan()`.\n * @returns Array of cut vertices.\n * @remarks Time O(C), Space O(1)\n */\n getCutVertices() {\n return this.tarjan().cutVertices;\n }\n\n /**\n * DFN index map computed by `tarjan()`.\n * @returns Map from vertex to DFN index.\n * @remarks Time O(V), Space O(V)\n */\n getDFNMap() {\n return this.tarjan().dfnMap;\n }\n\n /**\n * LOW link map computed by `tarjan()`.\n * @returns Map from vertex to LOW value.\n * @remarks Time O(V), Space O(V)\n */\n getLowMap() {\n return this.tarjan().lowMap;\n }\n\n /**\n * Internal hook to attach an undirected edge into adjacency maps.\n * @param edge - Edge instance.\n * @returns `true` if both endpoints exist; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addEdge(edge: EO): boolean {\n for (const end of edge.endpoints) {\n const endVertex = this._getVertex(end);\n if (endVertex === undefined) return false;\n if (endVertex) {\n const edgeMap = this._edgeMap.get(endVertex);\n if (edgeMap) {\n edgeMap.push(edge);\n } else {\n this._edgeMap.set(endVertex, [edge]);\n }\n }\n }\n return true;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { MapGraphCoordinate, VertexKey } from '../../types';\nimport { DirectedEdge, DirectedGraph, DirectedVertex } from './directed-graph';\n\nexport class MapVertex<V = any> extends DirectedVertex<V> {\n lat: number;\n long: number;\n\n constructor(key: VertexKey, value: V, lat: number, long: number) {\n super(key, value);\n this.lat = lat;\n this.long = long;\n }\n}\n\nexport class MapEdge<E = any> extends DirectedEdge<E> {\n constructor(src: VertexKey, dest: VertexKey, weight?: number, value?: E) {\n super(src, dest, weight, value);\n }\n}\n\n/**\n * Directed graph variant carrying geospatial coordinates.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (MapVertex<V>).\n * @template EO - Concrete edge class (MapEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example examples will be generated by unit test\n */\nexport class MapGraph<\n V = any,\n E = any,\n VO extends MapVertex<V> = MapVertex<V>,\n EO extends MapEdge<E> = MapEdge<E>\n> extends DirectedGraph<V, E, VO, EO> {\n /**\n * Construct a MapGraph.\n * @param originCoord - Origin coordinate `[lat, long]` used as default.\n * @param bottomRight - Optional bottom-right coordinate for bounding boxes.\n * @remarks Time O(1), Space O(1)\n */\n constructor(originCoord: MapGraphCoordinate, bottomRight?: MapGraphCoordinate) {\n super();\n this._originCoord = originCoord;\n this._bottomRight = bottomRight;\n }\n\n protected _originCoord: MapGraphCoordinate = [0, 0];\n\n get originCoord(): MapGraphCoordinate {\n return this._originCoord;\n }\n\n protected _bottomRight: MapGraphCoordinate | undefined;\n\n get bottomRight(): MapGraphCoordinate | undefined {\n return this._bottomRight;\n }\n\n /**\n * Create a map vertex with optional coordinates.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @param lat - Latitude (defaults to `originCoord[0]`).\n * @param long - Longitude (defaults to `originCoord[1]`).\n * @returns MapVertex instance.\n * @remarks Time O(1), Space O(1)\n */\n override createVertex(\n key: VertexKey,\n value?: V,\n lat: number = this.originCoord[0],\n long: number = this.originCoord[1]\n ): VO {\n return new MapVertex(key, value, lat, long) as VO;\n }\n\n /**\n * Create a map edge (directed) with optional weight/value.\n * @param src - Source key.\n * @param dest - Destination key.\n * @param weight - Edge weight.\n * @param value - Edge payload.\n * @returns MapEdge instance.\n * @remarks Time O(1), Space O(1)\n */\n override createEdge(src: VertexKey, dest: VertexKey, weight?: number, value?: E): EO {\n return new MapEdge(src, dest, weight, value) as EO;\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Include `originCoord` and `bottomRight` so `clone()/filter()` preserve geospatial settings.\n * @returns Options bag extending super snapshot.\n * @remarks Time O(1), Space O(1)\n */\n protected override _snapshotOptions(): Record<string, unknown> {\n return { ...(super._snapshotOptions() as any), originCoord: this.originCoord, bottomRight: this.bottomRight };\n }\n\n /**\n * Re-create a same-species MapGraph instance from snapshot options.\n * @param options - Snapshot options providing `originCoord`/`bottomRight`.\n * @returns Empty MapGraph instance of `this` type.\n * @remarks Time O(1), Space O(1)\n */\n protected override _createInstance(options?: Partial<Record<string, unknown>>): this {\n const { originCoord, bottomRight } = (options || {}) as {\n originCoord?: [number, number];\n bottomRight?: [number, number] | undefined;\n };\n const oc = (originCoord ?? this.originCoord) as [number, number];\n const br = (bottomRight ?? this.bottomRight) as [number, number] | undefined;\n return new MapGraph<V, E, VO, EO>(oc, br) as this;\n }\n}\n","export enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n // if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n // if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n BinaryTreeOptions,\n BinaryTreePrintOptions,\n BTNEntry,\n DFSOrderPattern,\n DFSStackItem,\n EntryCallback,\n FamilyPosition,\n IterationType,\n NodeCallback,\n NodeDisplayLayout,\n NodePredicate,\n OptNodeOrNull,\n RBTNColor,\n ToEntryFn,\n Trampoline\n} from '../../types';\nimport { IBinaryTree } from '../../interfaces';\nimport { isComparable, makeTrampoline, makeTrampolineThunk } from '../../utils';\nimport { Queue } from '../queue';\nimport { IterableEntryBase } from '../base';\nimport { DFSOperation, Range } from '../../common';\n\n/**\n * @template K - The type of the key.\n * @template V - The type of the value.\n */\nexport class BinaryTreeNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: BinaryTreeNode<K, V> = undefined;\n\n /**\n * Creates an instance of BinaryTreeNode.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key of the node.\n * @param [value] - The value associated with the key.\n */\n constructor(key: K, value?: V) {\n this.key = key;\n this.value = value;\n }\n\n _left?: BinaryTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the left child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The left child.\n */\n get left(): BinaryTreeNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Sets the left child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the left child.\n */\n set left(v: BinaryTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this as unknown as BinaryTreeNode<K, V>;\n }\n this._left = v;\n }\n\n _right?: BinaryTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the right child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The right child.\n */\n get right(): BinaryTreeNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Sets the right child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the right child.\n */\n set right(v: BinaryTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * A general Binary Tree implementation.\n *\n * @remarks\n * This class implements a basic Binary Tree, not a Binary Search Tree.\n * The `add` operation inserts nodes level-by-level (BFS) into the first available slot.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n * @template R - The type of the raw data object (if using `toEntryFn`).\n * 1. Two Children Maximum: Each node has at most two children.\n * 2. Left and Right Children: Nodes have distinct left and right children.\n * 3. Depth and Height: Depth is the number of edges from the root to a node; height is the maximum depth in the tree.\n * 4. Subtrees: Each child of a node forms the root of a subtree.\n * 5. Leaf Nodes: Nodes without children are leaves.\n *\n * @example\n * // basic BinaryTree creation and insertion\n * // Create a BinaryTree with entries\n * const entries: [number, string][] = [\n * [6, 'six'],\n * [1, 'one'],\n * [2, 'two'],\n * [7, 'seven'],\n * [5, 'five'],\n * [3, 'three'],\n * [4, 'four'],\n * [9, 'nine'],\n * [8, 'eight']\n * ];\n *\n * const tree = new BinaryTree(entries);\n *\n * // Verify size\n * console.log(tree.size); // 9;\n *\n * // Add new element\n * tree.add(10, 'ten');\n * console.log(tree.size); // 10;\n * @example\n * // BinaryTree get and has operations\n * const tree = new BinaryTree(\n * [\n * [5, 'five'],\n * [3, 'three'],\n * [7, 'seven'],\n * [1, 'one'],\n * [4, 'four'],\n * [6, 'six'],\n * [8, 'eight']\n * ],\n * { isMapMode: false }\n * );\n *\n * // Check if key exists\n * console.log(tree.has(5)); // true;\n * console.log(tree.has(10)); // false;\n *\n * // Get value by key\n * console.log(tree.get(3)); // 'three';\n * console.log(tree.get(7)); // 'seven';\n * console.log(tree.get(100)); // undefined;\n *\n * // Get node structure\n * const node = tree.getNode(5);\n * console.log(node?.key); // 5;\n * console.log(node?.value); // 'five';\n * @example\n * // BinaryTree level-order traversal\n * const tree = new BinaryTree([\n * [1, 'one'],\n * [2, 'two'],\n * [3, 'three'],\n * [4, 'four'],\n * [5, 'five'],\n * [6, 'six'],\n * [7, 'seven']\n * ]);\n *\n * // Binary tree maintains level-order insertion\n * // Complete binary tree structure\n * console.log(tree.size); // 7;\n *\n * // Verify all keys are present\n * console.log(tree.has(1)); // true;\n * console.log(tree.has(4)); // true;\n * console.log(tree.has(7)); // true;\n *\n * // Iterate through tree\n * const keys: number[] = [];\n * for (const [key] of tree) {\n * keys.push(key);\n * }\n * console.log(keys.length); // 7;\n * @example\n * // determine loan approval using a decision tree\n * // Decision tree structure\n * const loanDecisionTree = new BinaryTree<string>(\n * ['stableIncome', 'goodCredit', 'Rejected', 'Approved', 'Rejected'],\n * { isDuplicate: true }\n * );\n *\n * function determineLoanApproval(\n * node?: BinaryTreeNode<string> | null,\n * conditions?: { [key: string]: boolean }\n * ): string {\n * if (!node) throw new Error('Invalid node');\n *\n * // If it's a leaf node, return the decision result\n * if (!node.left && !node.right) return node.key;\n *\n * // Check if a valid condition exists for the current node's key\n * return conditions?.[node.key]\n * ? determineLoanApproval(node.left, conditions)\n * : determineLoanApproval(node.right, conditions);\n * }\n *\n * // Test case 1: Stable income and good credit score\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: true, goodCredit: true })); // 'Approved';\n *\n * // Test case 2: Stable income but poor credit score\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: true, goodCredit: false })); // 'Rejected';\n *\n * // Test case 3: No stable income\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: false, goodCredit: true })); // 'Rejected';\n *\n * // Test case 4: No stable income and poor credit score\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: false, goodCredit: false })); // 'Rejected';\n * @example\n * // evaluate the arithmetic expression represented by the binary tree\n * const expressionTree = new BinaryTree<number | string>(['+', 3, '*', null, null, 5, '-', null, null, 2, 8]);\n *\n * function evaluate(node?: BinaryTreeNode<number | string> | null): number {\n * if (!node) return 0;\n *\n * if (typeof node.key === 'number') return node.key;\n *\n * const leftValue = evaluate(node.left); // Evaluate the left subtree\n * const rightValue = evaluate(node.right); // Evaluate the right subtree\n *\n * // Perform the operation based on the current node's operator\n * switch (node.key) {\n * case '+':\n * return leftValue + rightValue;\n * case '-':\n * return leftValue - rightValue;\n * case '*':\n * return leftValue * rightValue;\n * case '/':\n * return rightValue !== 0 ? leftValue / rightValue : 0; // Handle division by zero\n * default:\n * throw new Error(`Unsupported operator: ${node.key}`);\n * }\n * }\n *\n * console.log(evaluate(expressionTree.root)); // -27;\n */\nexport class BinaryTree<K = any, V = any, R = any>\n extends IterableEntryBase<K, V | undefined>\n implements IBinaryTree<K, V, R>\n{\n iterationType: IterationType = 'ITERATIVE';\n\n /**\n * Creates an instance of BinaryTree.\n * @remarks Time O(N * M), where N is the number of items in `keysNodesEntriesOrRaws` and M is the tree size at insertion time (due to O(M) `add` operation). Space O(N) for storing the nodes.\n *\n * @param [keysNodesEntriesOrRaws=[]] - An iterable of items to add.\n * @param [options] - Configuration options for the tree.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: BinaryTreeOptions<K, V, R>\n ) {\n super();\n if (options) {\n const { iterationType, toEntryFn, isMapMode, isDuplicate } = options;\n if (iterationType) this.iterationType = iterationType;\n if (isMapMode !== undefined) this._isMapMode = isMapMode;\n if (isDuplicate !== undefined) this._isDuplicate = isDuplicate;\n if (typeof toEntryFn === 'function') this._toEntryFn = toEntryFn;\n else if (toEntryFn) throw TypeError('toEntryFn must be a function type');\n }\n\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected _isMapMode = true;\n\n /**\n * Gets whether the tree is in Map mode.\n * @remarks In Map mode (default), values are stored in an external Map, and nodes only hold keys. If false, values are stored directly on the nodes. Time O(1)\n *\n * @returns True if in Map mode, false otherwise.\n */\n get isMapMode() {\n return this._isMapMode;\n }\n\n protected _isDuplicate = false;\n\n /**\n * Gets whether the tree allows duplicate keys.\n * @remarks Time O(1)\n *\n * @returns True if duplicates are allowed, false otherwise.\n */\n get isDuplicate() {\n return this._isDuplicate;\n }\n\n protected _store = new Map<K, V | undefined>();\n\n /**\n * Gets the external value store (used in Map mode).\n * @remarks Time O(1)\n *\n * @returns The map storing key-value pairs.\n */\n get store() {\n return this._store;\n }\n\n protected _root?: BinaryTreeNode<K, V> | null | undefined;\n\n /**\n * Gets the root node of the tree.\n * @remarks Time O(1)\n *\n * @returns The root node.\n */\n get root(): BinaryTreeNode<K, V> | null | undefined {\n return this._root;\n }\n\n protected _size: number = 0;\n\n /**\n * Gets the number of nodes in the tree.\n * @remarks Time O(1)\n *\n * @returns The size of the tree.\n */\n get size(): number {\n return this._size;\n }\n\n protected _NIL: BinaryTreeNode<K, V> = new BinaryTreeNode<K, V>(NaN as K) as unknown as BinaryTreeNode<K, V>;\n\n /**\n * Gets the sentinel NIL node (used in self-balancing trees like Red-Black Tree).\n * @remarks Time O(1)\n *\n * @returns The NIL node.\n */\n get NIL(): BinaryTreeNode<K, V> {\n return this._NIL;\n }\n\n protected _toEntryFn?: ToEntryFn<K, V, R>;\n\n /**\n * Gets the function used to convert raw data objects (R) into [key, value] entries.\n * @remarks Time O(1)\n *\n * @returns The conversion function.\n */\n get toEntryFn() {\n return this._toEntryFn;\n }\n\n /**\n * (Protected) Creates a new node.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key for the new node.\n * @param [value] - The value for the new node (used if not in Map mode).\n * @returns The newly created node.\n */\n createNode(key: K, value?: V): BinaryTreeNode<K, V> {\n return new BinaryTreeNode<K, V>(key, this._isMapMode ? undefined : value);\n }\n\n /**\n * Creates a new, empty tree of the same type and configuration.\n * @remarks Time O(1) (excluding options cloning), Space O(1)\n *\n * @param [options] - Optional overrides for the new tree's options.\n * @returns A new, empty tree instance.\n */\n createTree(options?: Partial<BinaryTreeOptions<K, V, R>>): this {\n return this._createInstance<K, V, R>(options);\n }\n\n /**\n * Ensures the input is a node. If it's a key or entry, it searches for the node.\n * @remarks Time O(1) if a node is passed. O(N) if a key or entry is passed (due to `getNode` performing a full search). Space O(1) if iterative search, O(H) if recursive (where H is height, O(N) worst-case).\n *\n * @param keyNodeOrEntry - The item to resolve to a node.\n * @param [iterationType=this.iterationType] - The traversal method to use if searching.\n * @returns The resolved node, or null/undefined if not found or input is null/undefined.\n */\n ensureNode(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType: IterationType = this.iterationType\n ): BinaryTreeNode<K, V> | null | undefined {\n if (keyNodeOrEntry === null) return null;\n if (keyNodeOrEntry === undefined) return;\n if (keyNodeOrEntry === this._NIL) return;\n\n if (this.isNode(keyNodeOrEntry)) return keyNodeOrEntry;\n\n if (this.isEntry(keyNodeOrEntry)) {\n const key = keyNodeOrEntry[0];\n if (key === null) return null;\n if (key === undefined) return;\n return this.getNode(key, this._root, iterationType);\n }\n\n return this.getNode(keyNodeOrEntry, this._root, iterationType);\n }\n\n /**\n * Checks if the given item is a `BinaryTreeNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a node, false otherwise.\n */\n isNode(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BinaryTreeNode<K, V> {\n return keyNodeOrEntry instanceof BinaryTreeNode;\n }\n\n /**\n * Checks if the given item is a raw data object (R) that needs conversion via `toEntryFn`.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeEntryOrRaw - The item to check.\n * @returns True if it's a raw object, false otherwise.\n */\n isRaw(\n keyNodeEntryOrRaw: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n ): keyNodeEntryOrRaw is R {\n return this._toEntryFn !== undefined && typeof keyNodeEntryOrRaw === 'object';\n }\n\n /**\n * Checks if the given item is a \"real\" node (i.e., not null, undefined, or NIL).\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a real node, false otherwise.\n */\n isRealNode(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BinaryTreeNode<K, V> {\n if (keyNodeOrEntry === this._NIL || keyNodeOrEntry === null || keyNodeOrEntry === undefined) return false;\n return this.isNode(keyNodeOrEntry);\n }\n\n /**\n * Checks if the given item is either a \"real\" node or null.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a real node or null, false otherwise.\n */\n isRealNodeOrNull(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BinaryTreeNode<K, V> | null {\n return keyNodeOrEntry === null || this.isRealNode(keyNodeOrEntry);\n }\n\n /**\n * Checks if the given item is the sentinel NIL node.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's the NIL node, false otherwise.\n */\n isNIL(keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined): boolean {\n return keyNodeOrEntry === this._NIL;\n }\n\n /**\n * Checks if the given item is a `Range` object.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeEntryOrPredicate - The item to check.\n * @returns True if it's a Range, false otherwise.\n */\n isRange(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>\n | Range<K>\n ): keyNodeEntryOrPredicate is Range<K> {\n return keyNodeEntryOrPredicate instanceof Range;\n }\n\n /**\n * Checks if a node is a leaf (has no real children).\n * @remarks Time O(N) if a key/entry is passed (due to `ensureNode`). O(1) if a node is passed. Space O(1) or O(H) (from `ensureNode`).\n *\n * @param keyNodeOrEntry - The node to check.\n * @returns True if the node is a leaf, false otherwise.\n */\n isLeaf(keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined): boolean {\n keyNodeOrEntry = this.ensureNode(keyNodeOrEntry);\n if (keyNodeOrEntry === undefined) return false;\n if (keyNodeOrEntry === null) return true; // A null spot is considered a leaf\n return !this.isRealNode(keyNodeOrEntry.left) && !this.isRealNode(keyNodeOrEntry.right);\n }\n\n /**\n * Checks if the given item is a [key, value] entry pair.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's an entry, false otherwise.\n */\n isEntry(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BTNEntry<K, V> {\n return Array.isArray(keyNodeOrEntry) && keyNodeOrEntry.length === 2;\n }\n\n /**\n * Checks if the given key is valid (comparable or null).\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key to validate.\n * @returns True if the key is valid, false otherwise.\n */\n isValidKey(key: any): key is K {\n if (key === null) return true;\n return isComparable(key);\n }\n\n /**\n * Adds a new node to the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).\n *\n * @param keyNodeOrEntry - The key, node, or entry to add.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n add(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (newNode === undefined) return false;\n\n if (!this._root) {\n this._setRoot(newNode);\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size = 1;\n return true;\n }\n\n const queue = new Queue<BinaryTreeNode<K, V>>([this._root]);\n let potentialParent: BinaryTreeNode<K, V> | undefined;\n while (queue.length > 0) {\n const cur = queue.shift();\n\n if (!cur) continue;\n\n if (!this._isDuplicate) {\n if (newNode !== null && cur.key === newNode.key) {\n this._replaceNode(cur, newNode);\n if (this._isMapMode) this._setValue(cur.key, newValue);\n return true; // Replaced existing node\n }\n }\n\n if (potentialParent === undefined && (cur.left === undefined || cur.right === undefined)) {\n potentialParent = cur;\n }\n\n if (cur.left !== null) {\n if (cur.left) queue.push(cur.left);\n }\n if (cur.right !== null) {\n if (cur.right) queue.push(cur.right);\n }\n }\n\n if (potentialParent) {\n if (potentialParent.left === undefined) {\n potentialParent.left = newNode;\n } else if (potentialParent.right === undefined) {\n potentialParent.right = newNode;\n }\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n\n return false; // Should not happen if tree is not full?\n }\n\n /**\n * Adds or updates a new node to the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).\n *\n * @param keyNodeOrEntry - The key, node, or entry to add or update.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n set(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n return this.add(keyNodeOrEntry, value);\n }\n\n /**\n * Adds multiple items to the tree.\n * @remarks Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) `add` operation). Space O(M) (from `add`) + O(N) (for the `inserted` array).\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add.\n * @param [values] - An optional parallel iterable of values.\n * @returns An array of booleans indicating the success of each individual `add` operation.\n */\n addMany(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n >,\n values?: Iterable<V | undefined>\n ): boolean[] {\n const inserted: boolean[] = [];\n\n let valuesIterator: Iterator<V | undefined> | undefined;\n if (values) {\n valuesIterator = values[Symbol.iterator]();\n }\n\n for (let keyNodeEntryOrRaw of keysNodesEntriesOrRaws) {\n let value: V | undefined | null = undefined;\n\n if (valuesIterator) {\n const valueResult = valuesIterator.next();\n if (!valueResult.done) {\n value = valueResult.value;\n }\n }\n if (this.isRaw(keyNodeEntryOrRaw)) keyNodeEntryOrRaw = this._toEntryFn!(keyNodeEntryOrRaw);\n inserted.push(this.add(keyNodeEntryOrRaw, value));\n }\n\n return inserted;\n }\n\n /**\n * Adds or updates multiple items to the tree.\n * @remarks Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) `add` operation). Space O(M) (from `add`) + O(N) (for the `inserted` array).\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add or update.\n * @param [values] - An optional parallel iterable of values.\n * @returns An array of booleans indicating the success of each individual `add` operation.\n */\n setMany(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n >,\n values?: Iterable<V | undefined>\n ): boolean[] {\n return this.addMany(keysNodesEntriesOrRaws, values);\n }\n\n /**\n * Merges another tree into this one by adding all its nodes.\n * @remarks Time O(N * M), same as `addMany`, where N is the size of `anotherTree` and M is the size of this tree. Space O(M) (from `add`).\n *\n * @param anotherTree - The tree to merge.\n */\n merge(anotherTree: BinaryTree<K, V, R>) {\n this.addMany(anotherTree, []);\n }\n\n /**\n * Clears the tree and refills it with new items.\n * @remarks Time O(N) (for `clear`) + O(N * M) (for `addMany`) = O(N * M). Space O(M) (from `addMany`).\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add.\n * @param [values] - An optional parallel iterable of values.\n */\n refill(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n >,\n values?: Iterable<V | undefined>\n ): void {\n this.clear();\n this.addMany(keysNodesEntriesOrRaws, values);\n }\n\n /**\n * Deletes a node from the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation finds the node, and if it has two children, swaps it with the rightmost node of its left subtree (in-order predecessor) before deleting. Time O(N) in the worst case. O(N) to find the node (`getNode`) and O(H) (which is O(N) worst-case) to find the rightmost node. Space O(1) (if `getNode` is iterative, which it is).\n *\n * @param keyNodeOrEntry - The node to delete.\n * @returns An array containing deletion results (for compatibility with self-balancing trees).\n */\n delete(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[] {\n const deletedResult: BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[] = [];\n if (!this._root) return deletedResult;\n\n const curr = this.getNode(keyNodeOrEntry);\n if (!curr) return deletedResult;\n\n const parent: BinaryTreeNode<K, V> | undefined = curr?.parent;\n let needBalanced: BinaryTreeNode<K, V> | undefined;\n let orgCurrent: BinaryTreeNode<K, V> | undefined = curr;\n\n if (!curr.left && !curr.right && !parent) {\n // Deleting the root with no children\n this._setRoot(undefined);\n } else if (curr.left) {\n // Node has a left child (or two children)\n // Find the rightmost node in the left subtree\n const leftSubTreeRightMost = this.getRightMost(node => node, curr.left);\n if (leftSubTreeRightMost) {\n const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;\n // Swap properties\n orgCurrent = this._swapProperties(curr, leftSubTreeRightMost);\n // `orgCurrent` is now the node to be physically deleted (which was the rightmost)\n if (parentOfLeftSubTreeMax) {\n // Unlink the rightmost node\n if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost)\n parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;\n else parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;\n needBalanced = parentOfLeftSubTreeMax;\n }\n }\n } else if (parent) {\n // Node has no left child, but has a parent\n // Promote the right child (which could be null)\n const { familyPosition: fp } = curr;\n if (fp === 'LEFT' || fp === 'ROOT_LEFT') {\n parent.left = curr.right;\n } else if (fp === 'RIGHT' || fp === 'ROOT_RIGHT') {\n parent.right = curr.right;\n }\n needBalanced = parent;\n } else {\n // Deleting the root, which has no left child\n // Promote the right child as the new root\n this._setRoot(curr.right);\n curr.right = undefined;\n }\n\n this._size = this._size - 1;\n\n deletedResult.push({ deleted: orgCurrent, needBalanced });\n if (this._isMapMode && orgCurrent) this._store.delete(orgCurrent.key);\n return deletedResult;\n }\n\n search(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne?: boolean\n ): (K | undefined)[];\n\n search<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne: boolean,\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Searches the tree for nodes matching a predicate.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Performs a full DFS (pre-order) scan of the tree. Time O(N), as it may visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).\n *\n * @template C - The type of the callback function.\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [onlyOne=false] - If true, stops after finding the first match.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on matching nodes.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - Whether to use 'RECURSIVE' or 'ITERATIVE' search.\n * @returns An array of results from the callback function for each matching node.\n */\n search<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne = false,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n if (keyNodeEntryOrPredicate === undefined) return [];\n if (keyNodeEntryOrPredicate === null) return [];\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n const predicate = this._ensurePredicate(keyNodeEntryOrPredicate);\n\n const ans: ReturnType<C>[] = [];\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V>) => {\n if (predicate(cur)) {\n ans.push(callback(cur));\n if (onlyOne) return;\n }\n if (!this.isRealNode(cur.left) && !this.isRealNode(cur.right)) return;\n if (this.isRealNode(cur.left)) dfs(cur.left);\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(startNode);\n } else {\n const stack = [startNode];\n\n while (stack.length > 0) {\n const cur = stack.pop();\n if (this.isRealNode(cur)) {\n if (predicate(cur)) {\n ans.push(callback(cur));\n if (onlyOne) return ans;\n }\n if (this.isRealNode(cur.left)) stack.push(cur.left);\n if (this.isRealNode(cur.right)) stack.push(cur.right);\n }\n }\n }\n\n return ans;\n }\n\n /**\n * Gets all nodes matching a predicate.\n * @remarks Time O(N) (via `search`). Space O(H) or O(N) (via `search`).\n *\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [onlyOne=false] - If true, stops after finding the first match.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of matching nodes.\n */\n getNodes(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): BinaryTreeNode<K, V>[];\n\n getNodes(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne = false,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): (BinaryTreeNode<K, V> | null)[] {\n return this.search(keyNodeEntryOrPredicate, onlyOne, node => node, startNode, iterationType);\n }\n\n /**\n * Gets the first node matching a predicate.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via `search`). Space O(H) or O(N) (via `search`).\n *\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The first matching node, or undefined if not found.\n */\n getNode(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): BinaryTreeNode<K, V> | null | undefined {\n return this.search(keyNodeEntryOrPredicate, true, node => node, startNode, iterationType)[0];\n }\n\n /**\n * Gets the value associated with a key.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(1) if in Map mode. O(N) if not in Map mode (uses `getNode`). Space O(1) if in Map mode. O(H) or O(N) otherwise.\n *\n * @param keyNodeEntryOrPredicate - The key, node, or entry to get the value for.\n * @param [startNode=this._root] - The node to start searching from (if not in Map mode).\n * @param [iterationType=this.iterationType] - The traversal method (if not in Map mode).\n * @returns The associated value, or undefined.\n */\n override get(\n keyNodeEntryOrPredicate: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): V | undefined {\n if (this._isMapMode) {\n const key = this._extractKey(keyNodeEntryOrPredicate);\n if (key === null || key === undefined) return;\n return this._store.get(key);\n }\n return this.getNode(keyNodeEntryOrPredicate, startNode, iterationType)?.value;\n }\n\n /**\n * Checks if a node matching the predicate exists in the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via `search`). Space O(H) or O(N) (via `search`).\n *\n * @param [keyNodeEntryOrPredicate] - The key, node, entry, or predicate to check for.\n * @param [startNode] - The node to start the search from.\n * @param [iterationType] - The traversal method.\n * @returns True if a matching node exists, false otherwise.\n */\n override has(\n keyNodeEntryOrPredicate?:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): boolean;\n\n override has(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): boolean {\n return this.search(keyNodeEntryOrPredicate, true, node => node, startNode, iterationType).length > 0;\n }\n\n /**\n * Clears the tree of all nodes and values.\n * @remarks Time O(N) if in Map mode (due to `_store.clear()`), O(1) otherwise. Space O(1)\n */\n clear() {\n this._clearNodes();\n if (this._isMapMode) this._clearValues();\n }\n\n /**\n * Checks if the tree is empty.\n * @remarks Time O(1), Space O(1)\n *\n * @returns True if the tree has no nodes, false otherwise.\n */\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Checks if the tree is perfectly balanced.\n * @remarks A tree is perfectly balanced if the difference between min and max height is at most 1. Time O(N), as it requires two full traversals (`getMinHeight` and `getHeight`). Space O(H) or O(N) (from height calculation).\n *\n * @param [startNode=this._root] - The node to start checking from.\n * @returns True if perfectly balanced, false otherwise.\n */\n isPerfectlyBalanced(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ): boolean {\n return this.getMinHeight(startNode) + 1 >= this.getHeight(startNode);\n }\n\n /**\n * Checks if the tree is a valid Binary Search Tree (BST).\n * @remarks Time O(N), as it must visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).\n *\n * @param [startNode=this._root] - The node to start checking from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns True if it's a valid BST, false otherwise.\n */\n isBST(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): boolean {\n const startNodeSired = this.ensureNode(startNode);\n if (!startNodeSired) return true;\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V> | null | undefined, min: number, max: number): boolean => {\n if (!this.isRealNode(cur)) return true;\n const numKey = Number(cur.key);\n if (numKey <= min || numKey >= max) return false;\n return dfs(cur.left, min, numKey) && dfs(cur.right, numKey, max);\n };\n\n const isStandardBST = dfs(startNodeSired, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);\n const isInverseBST = dfs(startNodeSired, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER); // Check for reverse BST\n return isStandardBST || isInverseBST;\n } else {\n // Iterative in-order traversal check\n const checkBST = (checkMax = false) => {\n const stack: BinaryTreeNode<K, V>[] = [];\n let prev = checkMax ? Number.MAX_SAFE_INTEGER : Number.MIN_SAFE_INTEGER;\n let curr: BinaryTreeNode<K, V> | null | undefined = startNodeSired;\n while (this.isRealNode(curr) || stack.length > 0) {\n while (this.isRealNode(curr)) {\n stack.push(curr);\n curr = curr.left;\n }\n curr = stack.pop()!;\n const numKey = Number(curr.key);\n if (!this.isRealNode(curr) || (!checkMax && prev >= numKey) || (checkMax && prev <= numKey)) return false;\n prev = numKey;\n curr = curr.right;\n }\n return true;\n };\n const isStandardBST = checkBST(false);\n const isInverseBST = checkBST(true);\n return isStandardBST || isInverseBST;\n }\n }\n\n /**\n * Gets the depth of a node (distance from `startNode`).\n * @remarks Time O(H), where H is the depth of the `dist` node relative to `startNode`. O(N) worst-case. Space O(1).\n *\n * @param dist - The node to find the depth of.\n * @param [startNode=this._root] - The node to measure depth from (defaults to root).\n * @returns The depth (0 if `dist` is `startNode`).\n */\n getDepth(\n dist: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ): number {\n let distEnsured = this.ensureNode(dist);\n const beginRootEnsured = this.ensureNode(startNode);\n let depth = 0;\n while (distEnsured?.parent) {\n if (distEnsured === beginRootEnsured) {\n return depth;\n }\n depth++;\n distEnsured = distEnsured.parent;\n }\n return depth;\n }\n\n /**\n * Gets the maximum height of the tree (longest path from startNode to a leaf).\n * @remarks Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative stack (storing node + depth).\n *\n * @param [startNode=this._root] - The node to start measuring from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The height ( -1 for an empty tree, 0 for a single-node tree).\n */\n getHeight(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): number {\n startNode = this.ensureNode(startNode);\n if (!this.isRealNode(startNode)) return -1;\n\n if (iterationType === 'RECURSIVE') {\n const _getMaxHeight = (cur: BinaryTreeNode<K, V> | null | undefined): number => {\n if (!this.isRealNode(cur)) return -1;\n const leftHeight = _getMaxHeight(cur.left);\n const rightHeight = _getMaxHeight(cur.right);\n return Math.max(leftHeight, rightHeight) + 1;\n };\n\n return _getMaxHeight(startNode);\n } else {\n // Iterative (using DFS)\n const stack: { node: BinaryTreeNode<K, V>; depth: number }[] = [{ node: startNode, depth: 0 }];\n let maxHeight = 0;\n\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n\n if (this.isRealNode(node.left)) stack.push({ node: node.left, depth: depth + 1 });\n if (this.isRealNode(node.right)) stack.push({ node: node.right, depth: depth + 1 });\n\n maxHeight = Math.max(maxHeight, depth);\n }\n\n return maxHeight;\n }\n }\n\n /**\n * Gets the minimum height of the tree (shortest path from startNode to a leaf).\n * @remarks Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative (due to `depths` Map).\n *\n * @param [startNode=this._root] - The node to start measuring from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The minimum height (-1 for empty, 0 for single node).\n */\n getMinHeight(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): number {\n startNode = this.ensureNode(startNode);\n if (!startNode) return -1;\n\n if (iterationType === 'RECURSIVE') {\n const _getMinHeight = (cur: BinaryTreeNode<K, V> | null | undefined): number => {\n if (!this.isRealNode(cur)) return 0;\n if (!this.isRealNode(cur.left) && !this.isRealNode(cur.right)) return 0; // Leaf node\n const leftMinHeight = _getMinHeight(cur.left);\n const rightMinHeight = _getMinHeight(cur.right);\n return Math.min(leftMinHeight, rightMinHeight) + 1;\n };\n\n return _getMinHeight(startNode);\n } else {\n // Iterative (using post-order DFS)\n const stack: BinaryTreeNode<K, V>[] = [];\n let node: BinaryTreeNode<K, V> | null | undefined = startNode,\n last: BinaryTreeNode<K, V> | null | undefined = null;\n const depths: Map<BinaryTreeNode<K, V>, number> = new Map();\n\n while (stack.length > 0 || node) {\n if (this.isRealNode(node)) {\n stack.push(node);\n node = node.left;\n } else {\n node = stack[stack.length - 1];\n if (!this.isRealNode(node.right) || last === node.right) {\n node = stack.pop();\n if (this.isRealNode(node)) {\n const leftMinHeight = this.isRealNode(node.left) ? depths.get(node.left)! : -1;\n const rightMinHeight = this.isRealNode(node.right) ? depths.get(node.right)! : -1;\n depths.set(node, 1 + Math.min(leftMinHeight, rightMinHeight));\n last = node;\n node = null;\n }\n } else node = node.right;\n }\n }\n\n return depths.get(startNode)!;\n }\n }\n\n getPathToRoot(\n beginNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): (K | undefined)[];\n\n getPathToRoot<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n beginNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n callback: C,\n isReverse?: boolean\n ): ReturnType<C>[];\n\n /**\n * Gets the path from a given node up to the root.\n * @remarks Time O(H), where H is the depth of the `beginNode`. O(N) worst-case. Space O(H) for the result array.\n *\n * @template C - The type of the callback function.\n * @param beginNode - The node to start the path from.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on each node in the path.\n * @param [isReverse=false] - If true, returns the path from root-to-node.\n * @returns An array of callback results.\n */\n getPathToRoot<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n beginNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n isReverse = false\n ): ReturnType<C>[] {\n const result: ReturnType<C>[] = [];\n let beginNodeEnsured = this.ensureNode(beginNode);\n\n if (!beginNodeEnsured) return result;\n\n while (beginNodeEnsured.parent) {\n result.push(callback(beginNodeEnsured));\n beginNodeEnsured = beginNodeEnsured.parent;\n }\n result.push(callback(beginNodeEnsured)); // Add the root\n return isReverse ? result.reverse() : result;\n }\n\n getLeftMost(): K | undefined;\n\n getLeftMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n /**\n * Finds the leftmost node in a subtree (the node with the smallest key in a BST).\n * @remarks Time O(H), where H is the height of the left spine. O(N) worst-case. Space O(H) for recursive/trampoline stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on the leftmost node.\n * @param [startNode=this._root] - The subtree root to search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The callback result for the leftmost node.\n */\n getLeftMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C> {\n if (this.isNIL(startNode)) return callback(undefined);\n const ensuredStartNode = this.ensureNode(startNode);\n\n if (!this.isRealNode(ensuredStartNode)) return callback(undefined);\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {\n const { left } = cur;\n if (!this.isRealNode(left)) return cur;\n return dfs(left);\n };\n\n return callback(dfs(ensuredStartNode));\n } else {\n // Iterative (trampolined to prevent stack overflow, though 'ITERATIVE' usually means a loop)\n const dfs = makeTrampoline((cur: BinaryTreeNode<K, V>): Trampoline<BinaryTreeNode<K, V>> => {\n const { left } = cur;\n if (!this.isRealNode(left)) return cur;\n return makeTrampolineThunk(() => dfs(left));\n });\n\n return callback(dfs(ensuredStartNode));\n }\n }\n\n getRightMost(): K | undefined;\n\n getRightMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n /**\n * Finds the rightmost node in a subtree (the node with the largest key in a BST).\n * @remarks Time O(H), where H is the height of the right spine. O(N) worst-case. Space O(H) for recursive/trampoline stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on the rightmost node.\n * @param [startNode=this._root] - The subtree root to search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The callback result for the rightmost node.\n */\n getRightMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C> {\n if (this.isNIL(startNode)) return callback(undefined);\n startNode = this.ensureNode(startNode);\n if (!startNode) return callback(undefined);\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {\n const { right } = cur;\n if (!this.isRealNode(right)) return cur;\n return dfs(right);\n };\n\n return callback(dfs(startNode));\n } else {\n const dfs = makeTrampoline((cur: BinaryTreeNode<K, V>): Trampoline<BinaryTreeNode<K, V>> => {\n const { right } = cur;\n if (!this.isRealNode(right)) return cur;\n return makeTrampolineThunk(() => dfs(right));\n });\n\n return callback(dfs(startNode));\n }\n }\n\n /**\n * Gets the Morris traversal predecessor (rightmost node in the left subtree, or node itself).\n * @remarks This is primarily a helper for Morris traversal. Time O(H), where H is the height of the left subtree. O(N) worst-case. Space O(1).\n *\n * @param node - The node to find the predecessor for.\n * @returns The Morris predecessor.\n */\n getPredecessor(node: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> {\n if (this.isRealNode(node.left)) {\n let predecessor: BinaryTreeNode<K, V> | null | undefined = node.left;\n while (!this.isRealNode(predecessor) || (this.isRealNode(predecessor.right) && predecessor.right !== node)) {\n if (this.isRealNode(predecessor)) {\n predecessor = predecessor.right;\n }\n }\n return predecessor;\n } else {\n return node;\n }\n }\n\n /**\n * Gets the in-order successor of a node in a BST.\n * @remarks Time O(H), where H is the tree height. O(N) worst-case. Space O(H) (due to `getLeftMost` stack).\n *\n * @param [x] - The node to find the successor of.\n * @returns The successor node, or null/undefined if none exists.\n */\n getSuccessor(x?: K | BinaryTreeNode<K, V> | null): BinaryTreeNode<K, V> | null | undefined {\n x = this.ensureNode(x);\n if (!this.isRealNode(x)) return undefined;\n\n if (this.isRealNode(x.right)) {\n return this.getLeftMost(node => node, x.right);\n }\n\n let y: BinaryTreeNode<K, V> | null | undefined = x.parent;\n while (this.isRealNode(y) && x === y.right) {\n x = y;\n y = y.parent;\n }\n return y;\n }\n\n dfs(): (K | undefined)[];\n\n dfs<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n dfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback?: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: boolean\n ): ReturnType<C>[];\n\n /**\n * Performs a Depth-First Search (DFS) traversal.\n * @remarks Time O(N), visits every node. Space O(H) for the call/explicit stack. O(N) worst-case.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [pattern='IN'] - The traversal order ('IN', 'PRE', 'POST').\n * @param [onlyOne=false] - If true, stops after the first callback.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @param [includeNull=false] - If true, includes null nodes in the traversal.\n * @returns An array of callback results.\n */\n dfs<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n onlyOne: boolean = false,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n return this._dfs(callback, pattern, onlyOne, startNode, iterationType, includeNull);\n }\n\n bfs(): (K | undefined)[];\n\n bfs<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: false\n ): ReturnType<C>[];\n\n bfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: true\n ): ReturnType<C>[];\n\n /**\n * Performs a Breadth-First Search (BFS) or Level-Order traversal.\n * @remarks Time O(N), visits every node. Space O(N) in the worst case for the queue (e.g., a full last level).\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method ('RECURSIVE' BFS is less common but supported here).\n * @param [includeNull=false] - If true, includes null nodes in the traversal.\n * @returns An array of callback results.\n */\n bfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n\n const ans: ReturnType<NodeCallback<BinaryTreeNode<K, V> | null>>[] = [];\n\n if (iterationType === 'RECURSIVE') {\n // This is a \"recursive\" BFS, which is atypical. It uses a queue but calls itself.\n const queue: Queue<OptNodeOrNull<BinaryTreeNode<K, V>>> = new Queue<OptNodeOrNull<BinaryTreeNode<K, V>>>([\n startNode\n ]);\n\n const dfs = (level: number) => {\n if (queue.length === 0) return;\n\n const current = queue.shift()!;\n ans.push(callback(current));\n\n if (includeNull) {\n if (current && this.isRealNodeOrNull(current.left)) queue.push(current.left);\n if (current && this.isRealNodeOrNull(current.right)) queue.push(current.right);\n } else {\n if (this.isRealNode(current.left)) queue.push(current.left);\n if (this.isRealNode(current.right)) queue.push(current.right);\n }\n\n dfs(level + 1);\n };\n\n dfs(0);\n } else {\n // Standard iterative BFS\n const queue = new Queue<OptNodeOrNull<BinaryTreeNode<K, V>>>([startNode]);\n while (queue.length > 0) {\n const levelSize = queue.length; // Not strictly needed here, but good for level-by-level\n for (let i = 0; i < levelSize; i++) {\n const current = queue.shift()!;\n ans.push(callback(current));\n\n if (includeNull) {\n if (current && this.isRealNodeOrNull(current.left)) queue.push(current.left);\n if (current && this.isRealNodeOrNull(current.right)) queue.push(current.right);\n } else {\n if (this.isRealNode(current.left)) queue.push(current.left);\n if (this.isRealNode(current.right)) queue.push(current.right);\n }\n }\n }\n }\n return ans;\n }\n\n leaves(): (K | undefined)[];\n\n leaves<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Finds all leaf nodes in the tree.\n * @remarks Time O(N), visits every node. Space O(H) for recursive stack or O(N) for iterative queue.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each leaf node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n leaves<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n const leaves: ReturnType<NodeCallback<BinaryTreeNode<K, V> | null>>[] = [];\n\n if (!this.isRealNode(startNode)) return [];\n\n if (iterationType === 'RECURSIVE') {\n // DFS-based\n const dfs = (cur: BinaryTreeNode<K, V>) => {\n if (this.isLeaf(cur)) {\n leaves.push(callback(cur));\n }\n if (!this.isRealNode(cur.left) && !this.isRealNode(cur.right)) return;\n if (this.isRealNode(cur.left)) dfs(cur.left);\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(startNode);\n } else {\n // BFS-based\n const queue = new Queue([startNode]);\n\n while (queue.length > 0) {\n const cur = queue.shift();\n if (this.isRealNode(cur)) {\n if (this.isLeaf(cur)) {\n leaves.push(callback(cur));\n }\n if (this.isRealNode(cur.left)) queue.push(cur.left);\n if (this.isRealNode(cur.right)) queue.push(cur.right);\n }\n }\n }\n\n return leaves;\n }\n\n listLevels(): (K | undefined)[][];\n\n listLevels<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: false\n ): ReturnType<C>[][];\n\n listLevels<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: true\n ): ReturnType<C>[][];\n\n /**\n * Returns a 2D array of nodes, grouped by level.\n * @remarks Time O(N), visits every node. Space O(N) for the result array and the queue/stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @param [includeNull=false] - If true, includes null nodes.\n * @returns A 2D array of callback results.\n */\n listLevels<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false\n ): ReturnType<C>[][] {\n startNode = this.ensureNode(startNode);\n const levelsNodes: ReturnType<C>[][] = [];\n\n if (!startNode) return levelsNodes;\n\n if (iterationType === 'RECURSIVE') {\n // Pre-order DFS based level listing\n const _recursive = (node: BinaryTreeNode<K, V> | null, level: number) => {\n if (!levelsNodes[level]) levelsNodes[level] = [];\n levelsNodes[level].push(callback(node));\n if (includeNull) {\n if (node && this.isRealNodeOrNull(node.left)) _recursive(node.left, level + 1);\n if (node && this.isRealNodeOrNull(node.right)) _recursive(node.right, level + 1);\n } else {\n if (node && node.left) _recursive(node.left, level + 1);\n if (node && node.right) _recursive(node.right, level + 1);\n }\n };\n\n _recursive(startNode, 0);\n } else {\n // Iterative DFS based level listing\n const stack: [BinaryTreeNode<K, V> | null, number][] = [[startNode, 0]];\n\n while (stack.length > 0) {\n const head = stack.pop()!;\n const [node, level] = head;\n\n if (!levelsNodes[level]) levelsNodes[level] = [];\n levelsNodes[level].push(callback(node));\n\n if (includeNull) {\n if (node && this.isRealNodeOrNull(node.right)) stack.push([node.right, level + 1]);\n if (node && this.isRealNodeOrNull(node.left)) stack.push([node.left, level + 1]);\n } else {\n if (node && node.right) stack.push([node.right, level + 1]);\n if (node && node.left) stack.push([node.left, level + 1]);\n }\n }\n }\n\n return levelsNodes;\n }\n\n morris(): (K | undefined)[];\n\n morris<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n pattern?: DFSOrderPattern,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): ReturnType<C>[];\n\n /**\n * Performs a Morris (threaded) traversal.\n * @remarks This traversal uses O(1) extra space (excluding the result array) by temporarily modifying the tree's right child pointers. Time O(N), as each node is visited a constant number of times. Space O(1) (excluding the `ans` array).\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [pattern='IN'] - The traversal order ('IN', 'PRE', 'POST').\n * @param [startNode=this._root] - The node to start from.\n * @returns An array of callback results.\n */\n morris<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n\n if (!startNode) return [];\n const ans: ReturnType<NodeCallback<BinaryTreeNode<K, V> | null>>[] = [];\n\n let cur: BinaryTreeNode<K, V> | null | undefined = startNode;\n\n // Helper to reverse a linked list (formed by right pointers)\n const _reverseEdge = (node: BinaryTreeNode<K, V> | null | undefined) => {\n let pre: BinaryTreeNode<K, V> | null | undefined = null;\n let next: BinaryTreeNode<K, V> | null | undefined = null;\n while (node) {\n next = node.right;\n node.right = pre;\n pre = node;\n node = next;\n }\n return pre;\n };\n\n // Helper to print the reversed edge (for post-order)\n const _printEdge = (node: BinaryTreeNode<K, V> | null | undefined) => {\n const tail: BinaryTreeNode<K, V> | null | undefined = _reverseEdge(node);\n let cur: BinaryTreeNode<K, V> | null | undefined = tail;\n\n while (cur) {\n ans.push(callback(cur));\n cur = cur.right;\n }\n\n _reverseEdge(tail); // Restore the edge\n };\n\n switch (pattern) {\n case 'IN':\n while (cur) {\n if (cur.left) {\n const predecessor = this.getPredecessor(cur);\n if (!predecessor.right) {\n // Create thread\n predecessor.right = cur;\n cur = cur.left;\n continue;\n } else {\n // Remove thread\n predecessor.right = null;\n }\n }\n ans.push(callback(cur));\n cur = cur.right;\n }\n break;\n case 'PRE':\n while (cur) {\n if (cur.left) {\n const predecessor = this.getPredecessor(cur);\n if (!predecessor.right) {\n // Create thread and visit\n predecessor.right = cur;\n ans.push(callback(cur));\n cur = cur.left;\n continue;\n } else {\n // Remove thread\n predecessor.right = null;\n }\n } else {\n ans.push(callback(cur));\n }\n cur = cur.right;\n }\n break;\n case 'POST':\n while (cur) {\n if (cur.left) {\n const predecessor = this.getPredecessor(cur);\n if (predecessor.right === null) {\n // Create thread\n predecessor.right = cur;\n cur = cur.left;\n continue;\n } else {\n // Remove thread and print right spine of left child\n predecessor.right = null;\n _printEdge(cur.left);\n }\n }\n cur = cur.right;\n }\n _printEdge(startNode); // Print the right spine of the root\n break;\n }\n return ans;\n }\n\n /**\n * Clones the tree.\n * @remarks Time O(N * M), where N is the number of nodes and M is the tree size during insertion (due to `bfs` + `add`, and `add` is O(M)). Space O(N) for the new tree and the BFS queue.\n *\n * @returns A new, cloned instance of the tree.\n */\n clone(): this {\n const out = this._createInstance<K, V, R>();\n this._clone(out);\n return out;\n }\n\n /**\n * Creates a new tree containing only the entries that satisfy the predicate.\n * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion (O(N) iteration + O(M) `add` for each item). Space O(N) for the new tree.\n *\n * @param predicate - A function to test each [key, value] pair.\n * @param [thisArg] - `this` context for the predicate.\n * @returns A new, filtered tree.\n */\n filter(predicate: EntryCallback<K, V | undefined, boolean>, thisArg?: unknown): this {\n const out = this._createInstance<K, V, R>();\n let i = 0;\n for (const [k, v] of this) if (predicate.call(thisArg, v, k, i++, this)) out.add([k, v]);\n return out;\n }\n\n /**\n * Creates a new tree by mapping each [key, value] pair to a new entry.\n * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion. Space O(N) for the new tree.\n *\n * @template MK - New key type.\n * @template MV - New value type.\n * @template MR - New raw type.\n * @param cb - A function to map each [key, value] pair.\n * @param [options] - Options for the new tree.\n * @param [thisArg] - `this` context for the callback.\n * @returns A new, mapped tree.\n */\n map<MK = K, MV = V, MR = any>(\n cb: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<BinaryTreeOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): BinaryTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let i = 0;\n for (const [k, v] of this) out.add(cb.call(thisArg, v, k, i++, this));\n return out;\n }\n\n /**\n * Generates a string representation of the tree for visualization.\n * @remarks Time O(N), visits every node. Space O(N*H) or O(N^2) in the worst case, as the string width can grow significantly.\n *\n * @param [startNode=this._root] - The node to start printing from.\n * @param [options] - Options to control the output (e.g., show nulls).\n * @returns The string representation of the tree.\n */\n override toVisual(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n options?: BinaryTreePrintOptions\n ): string {\n const opts = { isShowUndefined: false, isShowNull: true, isShowRedBlackNIL: false, ...options };\n startNode = this.ensureNode(startNode);\n let output = '';\n if (!startNode) return output;\n\n if (opts.isShowUndefined) output += `U for undefined\\n`;\n if (opts.isShowNull) output += `N for null\\n`;\n if (opts.isShowRedBlackNIL) output += `S for Sentinel Node(NIL)\\n`;\n\n const display = (root: BinaryTreeNode<K, V> | null | undefined): void => {\n const [lines] = this._displayAux(root, opts);\n let paragraph = '';\n for (const line of lines) {\n paragraph += line + '\\n';\n }\n output += paragraph;\n };\n\n display(startNode);\n return output;\n }\n\n /**\n * Prints a visual representation of the tree to the console.\n * @remarks Time O(N) (via `toVisual`). Space O(N*H) or O(N^2) (via `toVisual`).\n *\n * @param [options] - Options to control the output.\n * @param [startNode=this._root] - The node to start printing from.\n */\n override print(\n options?: BinaryTreePrintOptions,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ) {\n console.log(this.toVisual(startNode, options));\n }\n\n protected _dfs<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: boolean,\n shouldVisitLeft?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean,\n shouldVisitRight?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean,\n shouldVisitRoot?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean,\n shouldProcessRoot?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean\n ): ReturnType<C>[];\n\n /**\n * (Protected) Core DFS implementation.\n * @remarks Time O(N), visits every node satisfying predicates. Space O(H) for call/explicit stack. O(N) worst-case.\n *\n * @template C - Callback type.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on nodes.\n * @param [pattern='IN'] - Traversal order.\n * @param [onlyOne=false] - Stop after first match.\n * @param [startNode=this._root] - Starting node.\n * @param [iterationType=this.iterationType] - Traversal method.\n * @param [includeNull=false] - Include nulls.\n * @param [shouldVisitLeft] - Predicate to traverse left.\n * @param [shouldVisitRight] - Predicate to traverse right.\n * @param [shouldVisitRoot] - Predicate to visit root.\n * @param [shouldProcessRoot] - Predicate to process root.\n * @returns Array of callback results.\n */\n protected _dfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n onlyOne: boolean = false,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false,\n shouldVisitLeft: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => !!node,\n shouldVisitRight: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => !!node,\n shouldVisitRoot: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => {\n if (includeNull) return this.isRealNodeOrNull(node);\n return this.isRealNode(node);\n },\n shouldProcessRoot: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => this.isRealNodeOrNull(node)\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n const ans: ReturnType<C>[] = [];\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (node: BinaryTreeNode<K, V> | null) => {\n if (!shouldVisitRoot(node)) return;\n\n const visitLeft = () => {\n if (shouldVisitLeft(node) && node?.left !== undefined) dfs(node?.left);\n };\n const visitRight = () => {\n if (shouldVisitRight(node) && node?.right !== undefined) dfs(node?.right);\n };\n\n switch (pattern) {\n case 'IN':\n visitLeft();\n if (shouldProcessRoot(node)) {\n ans.push(callback(node));\n if (onlyOne) return;\n }\n visitRight();\n break;\n case 'PRE':\n if (shouldProcessRoot(node)) {\n ans.push(callback(node));\n if (onlyOne) return;\n }\n visitLeft();\n visitRight();\n break;\n case 'POST':\n visitLeft();\n visitRight();\n if (shouldProcessRoot(node)) {\n ans.push(callback(node));\n if (onlyOne) return;\n }\n break;\n }\n };\n\n dfs(startNode);\n } else {\n // Iterative\n const stack: DFSStackItem<BinaryTreeNode<K, V>>[] = [{ opt: DFSOperation.VISIT, node: startNode }];\n\n const pushLeft = (cur: DFSStackItem<BinaryTreeNode<K, V>>) => {\n if (shouldVisitLeft(cur.node)) stack.push({ opt: DFSOperation.VISIT, node: cur.node?.left });\n };\n const pushRight = (cur: DFSStackItem<BinaryTreeNode<K, V>>) => {\n if (shouldVisitRight(cur.node)) stack.push({ opt: DFSOperation.VISIT, node: cur.node?.right });\n };\n const pushRoot = (cur: DFSStackItem<BinaryTreeNode<K, V>>) => {\n if (shouldVisitRoot(cur.node)) stack.push({ opt: DFSOperation.PROCESS, node: cur.node });\n };\n\n while (stack.length > 0) {\n const cur = stack.pop();\n if (cur === undefined) continue;\n if (!shouldVisitRoot(cur.node)) continue;\n if (cur.opt === DFSOperation.PROCESS) {\n if (shouldProcessRoot(cur.node) && cur.node !== undefined) {\n ans.push(callback(cur.node));\n if (onlyOne) return ans;\n }\n } else {\n // VISIT\n switch (pattern) {\n case 'IN':\n pushRight(cur);\n pushRoot(cur);\n pushLeft(cur);\n break;\n case 'PRE':\n pushRight(cur);\n pushLeft(cur);\n pushRoot(cur);\n break;\n case 'POST':\n pushRoot(cur);\n pushRight(cur);\n pushLeft(cur);\n break;\n }\n }\n }\n }\n\n return ans;\n }\n\n /**\n * (Protected) Gets the iterator for the tree (default in-order).\n * @remarks Time O(N) for full iteration. O(H) to get the first element. Space O(H) for the iterative stack. O(H) for recursive stack.\n *\n * @param [node=this._root] - The node to start iteration from.\n * @returns An iterator for [key, value] pairs.\n */\n protected *_getIterator(node = this._root): IterableIterator<[K, V | undefined]> {\n if (!node) return;\n\n if (this.iterationType === 'ITERATIVE') {\n const stack: (BinaryTreeNode<K, V> | null | undefined)[] = [];\n let current: BinaryTreeNode<K, V> | null | undefined = node;\n\n while (current || stack.length > 0) {\n // Go to the leftmost node\n while (this.isRealNode(current)) {\n stack.push(current);\n current = current.left;\n }\n\n // Visit the node\n current = stack.pop();\n\n if (this.isRealNode(current)) {\n if (this._isMapMode) yield [current.key, this._store.get(current.key)];\n else yield [current.key, current.value];\n // Move to the right subtree\n current = current.right;\n }\n }\n } else {\n // Recursive in-order traversal\n if (node.left && this.isRealNode(node)) {\n yield* this[Symbol.iterator](node.left);\n }\n\n if (this._isMapMode) yield [node.key, this._store.get(node.key)];\n else yield [node.key, node.value];\n\n if (node.right && this.isRealNode(node)) {\n yield* this[Symbol.iterator](node.right);\n }\n }\n }\n\n /**\n * (Protected) Default callback function, returns the node's key.\n * @remarks Time O(1)\n *\n * @param node - The node.\n * @returns The node's key or undefined.\n */\n protected _DEFAULT_NODE_CALLBACK = (node: BinaryTreeNode<K, V> | null | undefined) => (node ? node.key : undefined);\n\n /**\n * (Protected) Snapshots the current tree's configuration options.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the options.\n * @returns The options object.\n */\n protected _snapshotOptions<TK = K, TV = V, TR = R>(): BinaryTreeOptions<TK, TV, TR> {\n return {\n iterationType: this.iterationType,\n toEntryFn: this.toEntryFn as unknown as BinaryTreeOptions<TK, TV, TR>['toEntryFn'],\n isMapMode: this.isMapMode,\n isDuplicate: this.isDuplicate\n };\n }\n\n /**\n * (Protected) Creates a new, empty instance of the same tree constructor.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [options] - Options for the new tree.\n * @returns A new, empty tree.\n */\n protected _createInstance<TK = K, TV = V, TR = R>(options?: Partial<BinaryTreeOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BinaryTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BinaryTreeOptions<TK, TV, TR>\n ) => BinaryTree<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Creates a new instance of the same tree constructor, potentially with different generic types.\n * @remarks Time O(N) (or as per constructor) due to processing the iterable.\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [iter=[]] - An iterable to populate the new tree.\n * @param [options] - Options for the new tree.\n * @returns A new tree.\n */\n protected _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | BinaryTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<BinaryTreeOptions<TK, TV, TR>>\n ): BinaryTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BinaryTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BinaryTreeOptions<TK, TV, TR>\n ) => BinaryTree<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as BinaryTree<\n TK,\n TV,\n TR\n >;\n }\n\n /**\n * (Protected) Converts a key, node, or entry into a standardized [node, value] tuple.\n * @remarks Time O(1)\n *\n * @param keyNodeOrEntry - The input item.\n * @param [value] - An optional value (used if input is just a key).\n * @returns A tuple of [node, value].\n */\n protected _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): [BinaryTreeNode<K, V> | null | undefined, V | undefined] {\n if (keyNodeOrEntry === undefined) return [undefined, undefined];\n if (keyNodeOrEntry === null) return [null, undefined];\n\n if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, entryValue] = keyNodeOrEntry;\n if (key === undefined) return [undefined, undefined];\n else if (key === null) return [null, undefined];\n const finalValue = value ?? entryValue;\n return [this.createNode(key, finalValue), finalValue];\n }\n\n return [this.createNode(keyNodeOrEntry, value), value];\n }\n\n /**\n * (Protected) Helper for cloning. Performs a BFS and adds all nodes to the new tree.\n * @remarks Time O(N * M) (O(N) BFS + O(M) `add` for each node).\n *\n * @param cloned - The new, empty tree instance to populate.\n */\n protected _clone(cloned: BinaryTree<K, V, R>) {\n // Use BFS with nulls to preserve the tree structure\n this.bfs(\n node => {\n if (node === null) cloned.add(null);\n else {\n if (this._isMapMode) cloned.add([node.key, this._store.get(node.key)]);\n else cloned.add([node.key, node.value]);\n }\n },\n this._root,\n this.iterationType,\n true // Include nulls\n );\n if (this._isMapMode) cloned._store = this._store;\n }\n\n /**\n * (Protected) Recursive helper for `toVisual`.\n * @remarks Time O(N), Space O(N*H) or O(N^2)\n *\n * @param node - The current node.\n * @param options - Print options.\n * @returns Layout information for this subtree.\n */\n protected _displayAux(\n node: BinaryTreeNode<K, V> | null | undefined,\n options: BinaryTreePrintOptions\n ): NodeDisplayLayout {\n const { isShowNull, isShowUndefined, isShowRedBlackNIL } = options;\n const emptyDisplayLayout = <NodeDisplayLayout>[['─'], 1, 0, 0]; // Represents an empty spot\n\n if (node === null && !isShowNull) {\n return emptyDisplayLayout;\n } else if (node === undefined && !isShowUndefined) {\n return emptyDisplayLayout;\n } else if (this.isNIL(node) && !isShowRedBlackNIL) {\n return emptyDisplayLayout;\n } else if (node !== null && node !== undefined) {\n // Real node\n const key = node.key,\n line = this.isNIL(node) ? 'S' : String(key),\n width = line.length;\n\n return _buildNodeDisplay(\n line,\n width,\n this._displayAux(node.left, options),\n this._displayAux(node.right, options)\n );\n } else {\n // Null or Undefined\n const line = node === undefined ? 'U' : 'N',\n width = line.length;\n\n // Treat as a leaf\n return _buildNodeDisplay(line, width, [[''], 1, 0, 0], [[''], 1, 0, 0]);\n }\n\n /**\n * (Inner) Builds the display lines for a node.\n * @remarks Time/Space: Proportional to the width and height of the subtrees.\n */\n function _buildNodeDisplay(line: string, width: number, left: NodeDisplayLayout, right: NodeDisplayLayout) {\n const [leftLines, leftWidth, leftHeight, leftMiddle] = left;\n const [rightLines, rightWidth, rightHeight, rightMiddle] = right;\n const firstLine =\n ' '.repeat(Math.max(0, leftMiddle + 1)) +\n '_'.repeat(Math.max(0, leftWidth - leftMiddle - 1)) +\n line +\n '_'.repeat(Math.max(0, rightMiddle)) +\n ' '.repeat(Math.max(0, rightWidth - rightMiddle));\n\n const secondLine =\n (leftHeight > 0\n ? ' '.repeat(leftMiddle) + '/' + ' '.repeat(leftWidth - leftMiddle - 1)\n : ' '.repeat(leftWidth)) +\n ' '.repeat(width) +\n (rightHeight > 0\n ? ' '.repeat(rightMiddle) + '\\\\' + ' '.repeat(rightWidth - rightMiddle - 1)\n : ' '.repeat(rightWidth));\n\n const mergedLines = [firstLine, secondLine];\n\n for (let i = 0; i < Math.max(leftHeight, rightHeight); i++) {\n const leftLine = i < leftHeight ? leftLines[i] : ' '.repeat(leftWidth);\n const rightLine = i < rightHeight ? rightLines[i] : ' '.repeat(rightWidth);\n mergedLines.push(leftLine + ' '.repeat(width) + rightLine);\n }\n\n return <NodeDisplayLayout>[\n mergedLines,\n leftWidth + width + rightWidth,\n Math.max(leftHeight, rightHeight) + 2,\n leftWidth + Math.floor(width / 2)\n ];\n }\n }\n\n /**\n * (Protected) Swaps the key/value properties of two nodes.\n * @remarks Time O(1)\n *\n * @param srcNode - The source node.\n * @param destNode - The destination node.\n * @returns The `destNode` (now holding `srcNode`'s properties).\n */\n protected _swapProperties(\n srcNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n destNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeNode<K, V> | undefined {\n srcNode = this.ensureNode(srcNode);\n destNode = this.ensureNode(destNode);\n\n if (srcNode && destNode) {\n const { key, value } = destNode;\n const tempNode = this.createNode(key, value); // Use a temp node to hold dest properties\n\n if (tempNode) {\n // Copy src to dest\n destNode.key = srcNode.key;\n if (!this._isMapMode) destNode.value = srcNode.value;\n\n // Copy temp (original dest) to src\n srcNode.key = tempNode.key;\n if (!this._isMapMode) srcNode.value = tempNode.value;\n }\n\n return destNode;\n }\n return undefined;\n }\n\n /**\n * (Protected) Replaces a node in the tree with a new node, maintaining children and parent links.\n * @remarks Time O(1)\n *\n * @param oldNode - The node to be replaced.\n * @param newNode - The node to insert.\n * @returns The `newNode`.\n */\n protected _replaceNode(oldNode: BinaryTreeNode<K, V>, newNode: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> {\n if (oldNode.parent) {\n if (oldNode.parent.left === oldNode) {\n oldNode.parent.left = newNode;\n } else if (oldNode.parent.right === oldNode) {\n oldNode.parent.right = newNode;\n }\n }\n newNode.left = oldNode.left;\n newNode.right = oldNode.right;\n newNode.parent = oldNode.parent;\n if (this._root === oldNode) {\n this._setRoot(newNode);\n }\n\n return newNode;\n }\n\n /**\n * (Protected) Sets the root node and clears its parent reference.\n * @remarks Time O(1)\n *\n * @param v - The node to set as root.\n */\n protected _setRoot(v: BinaryTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = undefined;\n }\n this._root = v;\n }\n\n /**\n * (Protected) Converts a key, node, entry, or predicate into a standardized predicate function.\n * @remarks Time O(1)\n *\n * @param keyNodeEntryOrPredicate - The item to convert.\n * @returns A predicate function.\n */\n protected _ensurePredicate(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>\n ): NodePredicate<BinaryTreeNode<K, V>>;\n\n protected _ensurePredicate(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>\n ): NodePredicate<BinaryTreeNode<K, V> | null> {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined)\n return (node: BinaryTreeNode<K, V> | null | undefined) => (node ? false : false);\n\n if (this._isPredicate(keyNodeEntryOrPredicate)) return keyNodeEntryOrPredicate;\n\n if (this.isRealNode(keyNodeEntryOrPredicate))\n return (node: BinaryTreeNode<K, V> | null) => node === keyNodeEntryOrPredicate;\n\n if (this.isEntry(keyNodeEntryOrPredicate)) {\n const [key] = keyNodeEntryOrPredicate;\n return (node: BinaryTreeNode<K, V> | null) => {\n if (!node) return false;\n return node.key === key;\n };\n }\n\n // Assume it's a key\n return (node: BinaryTreeNode<K, V> | null) => {\n if (!node) return false;\n return node.key === keyNodeEntryOrPredicate;\n };\n }\n\n /**\n * (Protected) Checks if an item is a predicate function.\n * @remarks Time O(1)\n *\n * @param p - The item to check.\n * @returns True if it's a function.\n */\n protected _isPredicate(p: any): p is NodePredicate<BinaryTreeNode<K, V>> {\n return typeof p === 'function';\n }\n\n /**\n * (Protected) Extracts the key from a key, node, or entry.\n * @remarks Time O(1)\n *\n * @param keyNodeOrEntry - The item.\n * @returns The extracted key.\n */\n protected _extractKey(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): K | null | undefined {\n if (keyNodeOrEntry === null) return null;\n if (keyNodeOrEntry === undefined) return;\n if (keyNodeOrEntry === this._NIL) return;\n if (this.isNode(keyNodeOrEntry)) return keyNodeOrEntry.key;\n\n if (this.isEntry(keyNodeOrEntry)) return keyNodeOrEntry[0];\n\n return keyNodeOrEntry;\n }\n\n /**\n * (Protected) Sets a value in the external store (Map mode).\n * @remarks Time O(1) (average for Map.set).\n *\n * @param key - The key.\n * @param value - The value.\n * @returns True if successful.\n */\n protected _setValue(key: K | null | undefined, value: V | undefined) {\n if (key === null || key === undefined) return false;\n if (value === undefined) return false; // Or allow setting undefined?\n return this._store.set(key, value);\n }\n\n /**\n * (Protected) Clears all nodes from the tree.\n * @remarks Time O(1)\n */\n protected _clearNodes() {\n this._setRoot(undefined);\n this._size = 0;\n }\n\n /**\n * (Protected) Clears all values from the external store.\n * @remarks Time O(N)\n */\n protected _clearValues() {\n this._store.clear();\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n BSTNOptKeyOrNode,\n BSTOptions,\n BTNRep,\n Comparator,\n CP,\n DFSOrderPattern,\n EntryCallback,\n FamilyPosition,\n IterationType,\n NodeCallback,\n NodePredicate,\n OptNode,\n RBTNColor\n} from '../../types';\nimport { BinaryTree } from './binary-tree';\nimport { IBinaryTree } from '../../interfaces';\nimport { Queue } from '../queue';\nimport { isComparable } from '../../utils';\nimport { Range } from '../../common';\n\n/**\n * Represents a Node in a Binary Search Tree.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n */\nexport class BSTNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: BSTNode<K, V> = undefined;\n\n /**\n * Creates an instance of BSTNode.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key of the node.\n * @param [value] - The value associated with the key.\n */\n constructor(key: K, value?: V) {\n this.key = key;\n this.value = value;\n }\n\n _left?: BSTNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the left child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The left child.\n */\n get left(): BSTNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Sets the left child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the left child.\n */\n set left(v: BSTNode<K, V> | null | undefined) {\n if (v) v.parent = this;\n this._left = v;\n }\n\n _right?: BSTNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the right child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The right child.\n */\n get right(): BSTNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Sets the right child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the right child.\n */\n set right(v: BSTNode<K, V> | null | undefined) {\n if (v) v.parent = this;\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Represents a Binary Search Tree (BST).\n * Keys are ordered, allowing for faster search operations compared to a standard Binary Tree.\n * @template K - The type of the key.\n * @template V - The type of the value.\n * @template R - The type of the raw data object (if using `toEntryFn`).\n *\n * 1. Node Order: Each node's left child has a lesser value, and the right child has a greater value.\n * 2. Unique Keys: No duplicate keys in a standard BST.\n * 3. Efficient Search: Enables quick search, minimum, and maximum operations.\n * 4. Inorder Traversal: Yields nodes in ascending order.\n * 5. Logarithmic Operations: Ideal operations like insertion, deletion, and searching are O(log n) time-efficient.\n * 6. Balance Variability: Can become unbalanced; special types maintain balance.\n * 7. No Auto-Balancing: Standard BSTs don't automatically balance themselves.\n *\n * @example\n * // basic BST creation and add operation\n * // Create a simple BST with numeric keys\n * const bst = new BST<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * bst.print();\n * // _______8__________\n * // / \\\n * // ___4___ ____12_____\n * // / \\ / \\\n * // _2_ _6_ _10__ _14__\n * // / \\ / \\ / \\ / \\\n * // 1 3 5 7 9 11 13 15__\n * // \\\n * // 16\n *\n * // Verify size\n * console.log(bst.size); // 16;\n *\n * // Add new elements\n * bst.add(17);\n * bst.add(0);\n * console.log(bst.size); // 18;\n *\n * // Verify keys are searchable\n * console.log(bst.has(11)); // true;\n * console.log(bst.has(100)); // false;\n * @example\n * // BST delete and search after deletion\n * const bst = new BST<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * // Delete a leaf node\n * bst.delete(1);\n * console.log(bst.has(1)); // false;\n *\n * // Delete a node with one child\n * bst.delete(2);\n * console.log(bst.has(2)); // false;\n *\n * // Delete a node with two children\n * bst.delete(3);\n * console.log(bst.has(3)); // false;\n *\n * // Size decreases with each deletion\n * console.log(bst.size); // 13;\n *\n * // Other nodes remain searchable\n * console.log(bst.has(11)); // true;\n * console.log(bst.has(15)); // true;\n * @example\n * // Merge 3 sorted datasets\n * const dataset1 = new BST<number, string>([\n * [1, 'A'],\n * [7, 'G']\n * ]);\n * const dataset2 = [\n * [2, 'B'],\n * [6, 'F']\n * ];\n * const dataset3 = new BST<number, string>([\n * [3, 'C'],\n * [5, 'E'],\n * [4, 'D']\n * ]);\n *\n * // Merge datasets into a single BinarySearchTree\n * const merged = new BST<number, string>(dataset1);\n * merged.addMany(dataset2);\n * merged.merge(dataset3);\n *\n * // Verify merged dataset is in sorted order\n * console.log([...merged.values()]); // ['A', 'B', 'C', 'D', 'E', 'F', 'G'];\n * @example\n * // BST with custom objects for expression evaluation\n * interface Expression {\n * id: number;\n * operator: string;\n * precedence: number;\n * }\n *\n * // BST efficiently stores and retrieves operators by precedence\n * const operatorTree = new BST<number, Expression>(\n * [\n * [1, { id: 1, operator: '+', precedence: 1 }],\n * [2, { id: 2, operator: '*', precedence: 2 }],\n * [3, { id: 3, operator: '/', precedence: 2 }],\n * [4, { id: 4, operator: '-', precedence: 1 }],\n * [5, { id: 5, operator: '^', precedence: 3 }]\n * ],\n * { isMapMode: false }\n * );\n *\n * console.log(operatorTree.size); // 5;\n *\n * // Quick lookup of operators\n * const mult = operatorTree.get(2);\n * console.log(mult?.operator); // '*';\n * console.log(mult?.precedence); // 2;\n *\n * // Check if operator exists\n * console.log(operatorTree.has(5)); // true;\n * console.log(operatorTree.has(99)); // false;\n *\n * // Retrieve operator by precedence level\n * const expNode = operatorTree.getNode(3);\n * console.log(expNode?.key); // 3;\n * console.log(expNode?.value?.precedence); // 2;\n *\n * // Delete operator and verify\n * operatorTree.delete(1);\n * console.log(operatorTree.has(1)); // false;\n * console.log(operatorTree.size); // 4;\n *\n * // Get tree height for optimization analysis\n * const treeHeight = operatorTree.getHeight();\n * console.log(treeHeight); // > 0;\n *\n * // Remaining operators are still accessible\n * const remaining = operatorTree.get(2);\n * console.log(remaining); // defined;\n * @example\n * // Find lowest common ancestor\n * const bst = new BST<number>([20, 10, 30, 5, 15, 25, 35, 3, 7, 12, 18]);\n *\n * // LCA helper function\n * const findLCA = (num1: number, num2: number): number | undefined => {\n * const path1 = bst.getPathToRoot(num1);\n * const path2 = bst.getPathToRoot(num2);\n * // Find the first common ancestor\n * return findFirstCommon(path1, path2);\n * };\n *\n * function findFirstCommon(arr1: (number | undefined)[], arr2: (number | undefined)[]): number | undefined {\n * for (const num of arr1) {\n * if (arr2.indexOf(num) !== -1) {\n * return num;\n * }\n * }\n * return undefined;\n * }\n *\n * // Assertions\n * console.log(findLCA(3, 10)); // 7;\n * console.log(findLCA(5, 35)); // 15;\n * console.log(findLCA(20, 30)); // 25;\n */\nexport class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Creates an instance of BST.\n * @remarks Time O(N log N) or O(N^2) depending on `isBalanceAdd` in `addMany` and input order. Space O(N).\n *\n * @param [keysNodesEntriesOrRaws=[]] - An iterable of items to add.\n * @param [options] - Configuration options for the BST, including comparator.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<K | BSTNode | [K | null | undefined, V | undefined] | null | undefined | R> = [],\n options?: BSTOptions<K, V, R>\n ) {\n super([], options);\n\n if (options) {\n // Use the 'in' operator to check if the field is present\n if ('comparator' in options && options.comparator !== undefined) {\n this._comparator = options.comparator;\n } else {\n this._comparator = this._createDefaultComparator();\n }\n } else {\n this._comparator = this._createDefaultComparator();\n }\n\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected override _root?: BSTNode<K, V> = undefined;\n\n /**\n * Gets the root node of the tree.\n * @remarks Time O(1)\n *\n * @returns The root node.\n */\n override get root(): OptNode<BSTNode<K, V>> {\n return this._root;\n }\n\n /**\n * The comparator function used to determine the order of keys in the tree.\n\n * @remarks Time O(1) Space O(1)\n */\n protected _comparator: Comparator<K>;\n\n /**\n * Gets the comparator function used by the tree.\n * @remarks Time O(1)\n *\n * @returns The comparator function.\n */\n get comparator(): Comparator<K> {\n return this._comparator;\n }\n\n /**\n * (Protected) Creates a new BST node.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key for the new node.\n * @param [value] - The value for the new node (used if not in Map mode).\n * @returns The newly created BSTNode.\n */\n override createNode(key: K, value?: V): BSTNode<K, V> {\n return new BSTNode<K, V>(key, this._isMapMode ? undefined : value);\n }\n\n /**\n * Ensures the input is a node. If it's a key or entry, it searches for the node.\n * @remarks Time O(log N) (height of the tree), O(N) worst-case.\n *\n * @param keyNodeOrEntry - The item to resolve to a node.\n * @param [iterationType=this.iterationType] - The traversal method to use if searching.\n * @returns The resolved node, or undefined if not found.\n */\n override ensureNode(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType: IterationType = this.iterationType\n ): OptNode<BSTNode<K, V>> {\n return super.ensureNode(keyNodeOrEntry, iterationType) ?? undefined;\n }\n\n /**\n * Checks if the given item is a `BSTNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a BSTNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BSTNode<K, V> {\n return keyNodeOrEntry instanceof BSTNode;\n }\n\n /**\n * Checks if the given key is valid (comparable).\n * @remarks Time O(1)\n *\n * @param key - The key to validate.\n * @returns True if the key is valid, false otherwise.\n */\n override isValidKey(key: any): key is K {\n return isComparable(key);\n }\n\n override dfs(): (K | undefined)[];\n\n override dfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Performs a Depth-First Search (DFS) traversal.\n * @remarks Time O(N), visits every node. Space O(log N) for the call/explicit stack. O(N) worst-case.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [pattern='IN'] - The traversal order ('IN', 'PRE', 'POST').\n * @param [onlyOne=false] - If true, stops after the first callback.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n override dfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n onlyOne: boolean = false,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n return super.dfs(callback, pattern, onlyOne, startNode, iterationType);\n }\n\n override bfs(): (K | undefined)[];\n override bfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Performs a Breadth-First Search (BFS) or Level-Order traversal.\n * @remarks Time O(N), visits every node. Space O(N) in the worst case for the queue.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n override bfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n return super.bfs(callback, startNode, iterationType, false);\n }\n\n override listLevels(): (K | undefined)[][];\n\n override listLevels<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[][];\n\n /**\n * Returns a 2D array of nodes, grouped by level.\n * @remarks Time O(N), visits every node. Space O(N) for the result array and the queue/stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns A 2D array of callback results.\n */\n override listLevels<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[][] {\n return super.listLevels(callback, startNode, iterationType, false);\n }\n\n /**\n * Gets the first node matching a predicate.\n * @remarks Time O(log N) if searching by key, O(N) if searching by predicate. Space O(log N) or O(N).\n *\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The first matching node, or undefined if not found.\n */\n override getNode(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n startNode: BSTNOptKeyOrNode<K, BSTNode<K, V>> = this._root,\n iterationType: IterationType = this.iterationType\n ): OptNode<BSTNode<K, V>> {\n return this.getNodes(keyNodeEntryOrPredicate, true, startNode, iterationType)[0] ?? undefined;\n }\n\n override search(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne?: boolean\n ): (K | undefined)[];\n\n override search<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne: boolean,\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Searches the tree for nodes matching a predicate, key, or range.\n * @remarks This is an optimized search for a BST. If searching by key or range, it prunes branches.\n * Time O(H + M) for key/range search (H=height, M=matches). O(N) for predicate search.\n * Space O(log N) for the stack.\n *\n * @template C - The type of the callback function.\n * @param keyNodeEntryOrPredicate - The key, node, entry, predicate, or range to search for.\n * @param [onlyOne=false] - If true, stops after finding the first match.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on matching nodes.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - Whether to use 'RECURSIVE' or 'ITERATIVE' search.\n * @returns An array of results from the callback function for each matching node.\n */\n override search<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne = false,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n if (keyNodeEntryOrPredicate === undefined) return [];\n if (keyNodeEntryOrPredicate === null) return [];\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n\n let predicate: NodePredicate<BSTNode<K, V>>;\n const isRange = this.isRange(keyNodeEntryOrPredicate);\n\n if (isRange) {\n predicate = node => {\n if (!node) return false;\n return (keyNodeEntryOrPredicate as Range<K>).isInRange(node.key, this._comparator);\n };\n } else {\n predicate = this._ensurePredicate(keyNodeEntryOrPredicate);\n }\n\n // Optimization: Pruning logic\n const shouldVisitLeft = (cur: BSTNode<K, V> | null | undefined) => {\n if (!cur) return false;\n if (!this.isRealNode(cur.left)) return false;\n if (isRange) {\n // Range search: Only go left if the current key is >= the lower bound\n const range = keyNodeEntryOrPredicate as Range<K>;\n const leftS = range.low;\n const leftI = range.includeLow;\n return (leftI && this._compare(cur.key, leftS) >= 0) || (!leftI && this._compare(cur.key, leftS) > 0);\n }\n if (!isRange && !this._isPredicate(keyNodeEntryOrPredicate)) {\n // Key search: Only go left if current key > target key\n const benchmarkKey = this._extractKey(keyNodeEntryOrPredicate);\n return benchmarkKey !== null && benchmarkKey !== undefined && this._compare(cur.key, benchmarkKey) > 0;\n }\n return true; // Predicate search: must visit all\n };\n\n const shouldVisitRight = (cur: BSTNode<K, V> | null | undefined) => {\n if (!cur) return false;\n if (!this.isRealNode(cur.right)) return false;\n if (isRange) {\n // Range search: Only go right if current key <= upper bound\n const range = keyNodeEntryOrPredicate as Range<K>;\n const rightS = range.high;\n const rightI = range.includeHigh;\n return (rightI && this._compare(cur.key, rightS) <= 0) || (!rightI && this._compare(cur.key, rightS) < 0);\n }\n if (!isRange && !this._isPredicate(keyNodeEntryOrPredicate)) {\n // Key search: Only go right if current key < target key\n const benchmarkKey = this._extractKey(keyNodeEntryOrPredicate);\n return benchmarkKey !== null && benchmarkKey !== undefined && this._compare(cur.key, benchmarkKey) < 0;\n }\n return true; // Predicate search: must visit all\n };\n\n return super._dfs(\n callback,\n 'IN', // In-order is efficient for range/key search\n onlyOne,\n startNode,\n iterationType,\n false,\n shouldVisitLeft,\n shouldVisitRight,\n () => true, // shouldVisitRoot (always visit)\n cur => !!cur && predicate(cur) // shouldProcessRoot (only process if predicate matches)\n );\n }\n\n rangeSearch(range: Range<K> | [K, K]): (K | undefined)[];\n\n rangeSearch<C extends NodeCallback<BSTNode<K, V>>>(\n range: Range<K> | [K, K],\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Performs an optimized search for nodes within a given key range.\n * @remarks Time O(H + M), where H is tree height and M is the number of matches.\n *\n * @template C - The type of the callback function.\n * @param range - A `Range` object or a `[low, high]` tuple.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on matching nodes.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n rangeSearch<C extends NodeCallback<BSTNode<K, V>>>(\n range: Range<K> | [K, K],\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ) {\n const searchRange: Range<K> = range instanceof Range ? range : new Range(range[0], range[1]);\n return this.search(searchRange, false, callback, startNode, iterationType);\n }\n\n /**\n * Adds a new node to the BST based on key comparison.\n * @remarks Time O(log N), where H is tree height. O(N) worst-case (unbalanced tree), O(log N) average. Space O(1).\n *\n * @param keyNodeOrEntry - The key, node, or entry to add.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n override add(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (newNode === undefined) return false;\n\n if (this._root === undefined) {\n this._setRoot(newNode);\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n\n let current = this._root;\n while (current !== undefined) {\n if (this._compare(current.key, newNode.key) === 0) {\n // Key exists, replace node\n this._replaceNode(current, newNode);\n if (this._isMapMode) this._setValue(current.key, newValue);\n return true;\n } else if (this._compare(current.key, newNode.key) > 0) {\n // Go left\n if (current.left === undefined) {\n current.left = newNode;\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n if (current.left !== null) current = current.left;\n } else {\n // Go right\n if (current.right === undefined) {\n current.right = newNode;\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n if (current.right !== null) current = current.right;\n }\n }\n return false;\n }\n\n /**\n * Adds multiple items to the tree.\n * @remarks If `isBalanceAdd` is true, sorts the input and builds a balanced tree. Time O(N log N) (due to sort and balanced add).\n * If false, adds items one by one. Time O(N * H), which is O(N^2) worst-case.\n * Space O(N) for sorting and recursion/iteration stack.\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add.\n * @param [values] - An optional parallel iterable of values.\n * @param [isBalanceAdd=true] - If true, builds a balanced tree from the items.\n * @param [iterationType=this.iterationType] - The traversal method for balanced add (recursive or iterative).\n * @returns An array of booleans indicating the success of each individual `add` operation.\n */\n override addMany(\n keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, BSTNode<K, V>>>,\n values?: Iterable<V | undefined>,\n isBalanceAdd = true,\n iterationType: IterationType = this.iterationType\n ): boolean[] {\n const inserted: boolean[] = [];\n const valuesIterator: Iterator<V | undefined> | undefined = values?.[Symbol.iterator]();\n\n if (!isBalanceAdd) {\n // Standard O(N*H) insertion\n for (let kve of keysNodesEntriesOrRaws) {\n const val = valuesIterator?.next().value;\n if (this.isRaw(kve)) kve = this._toEntryFn!(kve);\n inserted.push(this.add(kve, val));\n }\n return inserted;\n }\n\n // Balanced O(N log N) insertion\n const realBTNExemplars: {\n key: R | K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined;\n value: V | undefined;\n orgIndex: number;\n }[] = [];\n\n let i = 0;\n for (const kve of keysNodesEntriesOrRaws) {\n realBTNExemplars.push({ key: kve, value: valuesIterator?.next().value, orgIndex: i++ });\n }\n\n // Sort items by key\n const sorted = realBTNExemplars.sort(({ key: a }, { key: b }) => {\n let keyA: K | undefined | null, keyB: K | undefined | null;\n if (this.isRaw(a)) keyA = this._toEntryFn!(a)[0];\n else if (this.isEntry(a)) keyA = a[0];\n else if (this.isRealNode(a)) keyA = a.key;\n else keyA = a as K;\n\n if (this.isRaw(b)) keyB = this._toEntryFn!(b)[0];\n else if (this.isEntry(b)) keyB = b[0];\n else if (this.isRealNode(b)) keyB = b.key;\n else keyB = b as K;\n\n if (keyA != null && keyB != null) return this._compare(keyA, keyB);\n return 0;\n });\n\n // Recursive balanced build\n const _dfs = (arr: typeof realBTNExemplars) => {\n if (arr.length === 0) return;\n const mid = Math.floor((arr.length - 1) / 2);\n const { key, value, orgIndex } = arr[mid];\n if (this.isRaw(key)) {\n const entry = this._toEntryFn!(key);\n inserted[orgIndex] = this.add(entry);\n } else {\n inserted[orgIndex] = this.add(key, value);\n }\n _dfs(arr.slice(0, mid));\n _dfs(arr.slice(mid + 1));\n };\n\n // Iterative balanced build\n const _iterate = () => {\n const n = sorted.length;\n const stack: Array<[number, number]> = [[0, n - 1]];\n while (stack.length > 0) {\n const popped = stack.pop();\n if (!popped) continue;\n const [l, r] = popped;\n if (l > r) continue;\n const m = l + Math.floor((r - l) / 2);\n const { key, value, orgIndex } = sorted[m];\n if (this.isRaw(key)) {\n const entry = this._toEntryFn!(key);\n inserted[orgIndex] = this.add(entry);\n } else {\n inserted[orgIndex] = this.add(key, value);\n }\n stack.push([m + 1, r]);\n stack.push([l, m - 1]);\n }\n };\n\n if (iterationType === 'RECURSIVE') _dfs(sorted);\n else _iterate();\n\n return inserted;\n }\n\n /**\n * Returns the first key with a value >= target.\n * Equivalent to Java TreeMap.ceiling.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n ceiling(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key >= target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n ceiling<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n ceiling<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n const node = this._bound(keyNodeEntryOrPredicate, true, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n /**\n * Returns the first key with a value > target.\n * Equivalent to Java TreeMap.higher.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n higher(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key > target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n higher<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n higher<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n const node = this._bound(keyNodeEntryOrPredicate, false, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n /**\n * Returns the first key with a value <= target.\n * Equivalent to Java TreeMap.floor.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n floor(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key <= target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n floor<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n floor<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n if (this._isPredicate(keyNodeEntryOrPredicate)) {\n const node = this._floorByPredicate(keyNodeEntryOrPredicate, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n let targetKey: K | undefined;\n if (this.isNode(keyNodeEntryOrPredicate)) {\n targetKey = keyNodeEntryOrPredicate.key;\n } else if (this.isEntry(keyNodeEntryOrPredicate)) {\n const key = keyNodeEntryOrPredicate[0];\n if (key === null || key === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n targetKey = key;\n } else {\n targetKey = keyNodeEntryOrPredicate;\n }\n\n if (targetKey !== undefined) {\n const node = this._floorByKey(targetKey, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n /**\n * Returns the first key with a value < target.\n * Equivalent to Java TreeMap.lower.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n lower(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key < target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n lower<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n lower<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback?: C | IterationType,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n if (this._isPredicate(keyNodeEntryOrPredicate)) {\n const node = this._lowerByPredicate(keyNodeEntryOrPredicate, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n let targetKey: K | undefined;\n if (this.isNode(keyNodeEntryOrPredicate)) {\n targetKey = keyNodeEntryOrPredicate.key;\n } else if (this.isEntry(keyNodeEntryOrPredicate)) {\n const key = keyNodeEntryOrPredicate[0];\n if (key === null || key === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n targetKey = key;\n } else {\n targetKey = keyNodeEntryOrPredicate;\n }\n\n if (targetKey !== undefined) {\n const node = this._lowerByKey(targetKey, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n lesserOrGreaterTraverse(): (K | undefined)[];\n\n lesserOrGreaterTraverse<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n lesserOrGreater?: number,\n targetNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Traverses the tree and returns nodes that are lesser or greater than a target node.\n * @remarks Time O(N), as it performs a full traversal. Space O(log N) or O(N).\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on matching nodes.\n * @param [lesserOrGreater=-1] - -1 for lesser, 1 for greater, 0 for equal.\n * @param [targetNode=this._root] - The node to compare against.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n lesserOrGreaterTraverse<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n lesserOrGreater: CP = -1,\n targetNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n const targetNodeEnsured = this.ensureNode(targetNode);\n const ans: ReturnType<NodeCallback<BSTNode<K, V>>>[] = [];\n if (!this._root || !targetNodeEnsured) return ans;\n\n const targetKey = targetNodeEnsured.key;\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BSTNode<K, V>) => {\n const compared = this._compare(cur.key, targetKey);\n if (Math.sign(compared) == lesserOrGreater) ans.push(callback(cur));\n\n if (this.isRealNode(cur.left)) dfs(cur.left);\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n dfs(this._root);\n return ans;\n } else {\n const queue = new Queue<BSTNode<K, V>>([this._root]);\n while (queue.length > 0) {\n const cur = queue.shift();\n if (this.isRealNode(cur)) {\n const compared = this._compare(cur.key, targetKey);\n if (Math.sign(compared) == lesserOrGreater) ans.push(callback(cur));\n if (this.isRealNode(cur.left)) queue.push(cur.left);\n if (this.isRealNode(cur.right)) queue.push(cur.right);\n }\n }\n return ans;\n }\n }\n\n /**\n * Rebuilds the tree to be perfectly balanced.\n * @remarks Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.\n *\n * @param [iterationType=this.iterationType] - The traversal method for the initial node export.\n * @returns True if successful, false if the tree was empty.\n */\n perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n this._clearNodes();\n if (n === 0) return false;\n\n // Build balanced tree from sorted array\n const build = (l: number, r: number, parent?: BSTNode<K, V>): BSTNode<K, V> | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m]! as BSTNode<K, V>;\n const leftChild = build(l, m - 1, root);\n const rightChild = build(m + 1, r, root);\n root.left = leftChild;\n root.right = rightChild;\n root.parent = parent;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n return true;\n }\n\n /**\n * Checks if the tree meets the AVL balance condition (height difference <= 1).\n * @remarks Time O(N), as it must visit every node to compute height. Space O(log N) for recursion or O(N) for iterative map.\n *\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns True if the tree is AVL balanced, false otherwise.\n */\n isAVLBalanced(iterationType: IterationType = this.iterationType): boolean {\n if (!this._root) return true;\n let balanced = true;\n\n if (iterationType === 'RECURSIVE') {\n // Recursive height check\n const _height = (cur: BSTNode<K, V> | null | undefined): number => {\n if (!cur) return 0;\n const leftHeight = _height(cur.left);\n const rightHeight = _height(cur.right);\n if (Math.abs(leftHeight - rightHeight) > 1) balanced = false;\n return Math.max(leftHeight, rightHeight) + 1;\n };\n _height(this._root);\n } else {\n // Iterative post-order height check\n const stack: BSTNode<K, V>[] = [];\n let node: OptNode<BSTNode<K, V>> = this._root,\n last: OptNode<BSTNode<K, V>> = undefined;\n const depths: Map<BSTNode<K, V>, number> = new Map();\n\n while (stack.length > 0 || node) {\n if (node) {\n stack.push(node);\n if (node.left !== null) node = node.left;\n } else {\n node = stack[stack.length - 1];\n if (!node.right || last === node.right) {\n node = stack.pop();\n if (node) {\n const left = node.left ? depths.get(node.left)! : -1;\n const right = node.right ? depths.get(node.right)! : -1;\n if (Math.abs(left - right) > 1) return false;\n depths.set(node, 1 + Math.max(left, right));\n last = node;\n node = undefined;\n }\n } else node = node.right;\n }\n }\n }\n return balanced;\n }\n\n /**\n * Creates a new BST by mapping each [key, value] pair to a new entry.\n * @remarks Time O(N * H), where N is nodes in this tree, and H is height of the new tree during insertion.\n * Space O(N) for the new tree.\n *\n * @template MK - New key type.\n * @template MV - New value type.\n * @template MR - New raw type.\n * @param callback - A function to map each [key, value] pair.\n * @param [options] - Options for the new BST.\n * @param [thisArg] - `this` context for the callback.\n * @returns A new, mapped BST.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<BSTOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): BST<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let index = 0;\n // Iterates in-order\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * Deletes nodes that match a key, node, entry, predicate, or range.\n *\n * @remarks\n * Time Complexity: O(N) for search + O(M log N) for M deletions, where N is tree size.\n * Space Complexity: O(M) for storing matched nodes and result map.\n *\n * @template K - The key type.\n * @template V - The value type.\n *\n * @param keyNodeEntryOrPredicate - The search criteria. Can be one of:\n * - A key (type K): searches for exact key match using the comparator.\n * - A BSTNode: searches for the matching node in the tree.\n * - An entry tuple: searches for the key-value pair.\n * - A NodePredicate function: tests each node and returns true for matches.\n * - A Range object: searches for nodes whose keys fall within the specified range (inclusive/exclusive based on range settings).\n * - null or undefined: treated as no match, returns empty results.\n *\n * @param onlyOne - If true, stops the search after finding the first match and only deletes that one node.\n * If false (default), searches for and deletes all matching nodes.\n *\n * @param startNode - The node to start the search from. Can be:\n * - A key, node, or entry: the method resolves it to a node and searches from that subtree.\n * - null or undefined: defaults to the root, searching the entire tree.\n * - Default value: this._root (the tree's root).\n *\n * @param iterationType - Controls the internal traversal implementation:\n * - 'RECURSIVE': uses recursive function calls for traversal.\n * - 'ITERATIVE': uses explicit stack-based iteration.\n * - Default: this.iterationType (the tree's default iteration mode).\n *\n * @returns A Map<K, boolean> containing the deletion results:\n * - Key: the matched node's key.\n * - Value: true if the deletion succeeded, false if it failed (e.g., key not found during deletion phase).\n * - If no nodes match the search criteria, the returned map is empty.\n */\n deleteWhere(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne = false,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): BinaryTreeDeleteResult<BSTNode<K, V>>[] {\n const toDelete = this.search(keyNodeEntryOrPredicate, onlyOne, node => node, startNode, iterationType);\n\n let results: BinaryTreeDeleteResult<BSTNode<K, V>>[] = [];\n for (const node of toDelete) {\n const deleteInfo = this.delete(node);\n results = results.concat(deleteInfo);\n }\n\n return results;\n }\n\n /**\n * (Protected) Creates the default comparator function for keys that don't have a custom comparator.\n * @remarks Time O(1) Space O(1)\n * @returns The default comparator function.\n */\n protected _createDefaultComparator(): Comparator<K> {\n return (a: K, b: K): number => {\n debugger;\n // If both keys are comparable (primitive types), use direct comparison\n if (isComparable(a) && isComparable(b)) {\n if (a > b) return 1;\n if (a < b) return -1;\n return 0;\n }\n\n // If keys are objects and no comparator is provided, throw an error\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object type keys, a custom comparator must be provided in the constructor's options!`\n );\n }\n\n // Default: keys are equal (fallback case)\n return 0;\n };\n }\n\n /**\n * (Protected) Binary search for floor by key with pruning optimization.\n * Performs standard BST binary search, choosing left or right subtree based on comparator result.\n * Finds first node where key <= target.\n * @remarks Time O(h) where h is tree height.\n *\n * @param key - The target key to search for.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node with key <= target, or undefined if none exists.\n */\n protected _floorByKey(key: K, iterationType: IterationType): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive binary search implementation\n const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {\n if (!this.isRealNode(cur)) return undefined;\n\n const cmp = this.comparator(cur.key!, key);\n\n if (cmp <= 0) {\n // Current node satisfies the floor condition (cur.key <= target).\n // Try to find a larger candidate in the right subtree.\n const rightResult = dfs(cur.right);\n return rightResult ?? cur;\n } else {\n // Current node is too large, move left to find smaller keys.\n return dfs(cur.left);\n }\n };\n\n return dfs(this.root);\n } else {\n // Iterative binary search implementation\n let current: BSTNode<K, V> | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (this.isRealNode(current)) {\n const cmp = this.comparator(current.key!, key);\n\n if (cmp <= 0) {\n // Current node is a candidate. Save it and try right subtree for a larger key.\n result = current;\n current = current.right ?? undefined;\n } else {\n // Current node is too large, move left.\n current = current.left ?? undefined;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) In-order traversal search for floor by predicate.\n * Falls back to linear in-order traversal when predicate-based search is required.\n * Returns the last node that satisfies the predicate function.\n * @remarks Time Complexity: O(n) since it may visit every node.\n * Space Complexity: O(h) for recursion, O(h) for iterative stack.\n *\n * @param predicate - The predicate function to test nodes.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The last node satisfying predicate (highest key), or undefined if none found.\n */\n protected _floorByPredicate(\n predicate: NodePredicate<BSTNode<K, V>>,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive in-order traversal\n let result: BSTNode<K, V> | undefined = undefined;\n\n const dfs = (cur: BSTNode<K, V> | null | undefined): void => {\n if (!this.isRealNode(cur)) return;\n\n // In-order: process left subtree first\n if (this.isRealNode(cur.left)) dfs(cur.left);\n\n // Check current node\n if (predicate(cur)) {\n result = cur;\n }\n\n // Process right subtree\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(this.root);\n return result;\n } else {\n // Iterative in-order traversal using explicit stack\n const stack: (BSTNode<K, V> | null | undefined)[] = [];\n let current: BSTNode<K, V> | null | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (stack.length > 0 || this.isRealNode(current)) {\n if (this.isRealNode(current)) {\n // Go to the leftmost node\n stack.push(current);\n current = current.left;\n } else {\n // Pop from stack and process\n const node = stack.pop();\n if (!this.isRealNode(node)) break;\n\n // Check if current node satisfies predicate\n if (predicate(node)) {\n result = node;\n }\n\n // Visit right subtree\n current = node.right;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) Binary search for lower by key with pruning optimization.\n * Performs standard BST binary search, choosing left or right subtree based on comparator result.\n * Finds first node where key < target.\n * @remarks Time O(h) where h is tree height.\n *\n * @param key - The target key to search for.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node with key < target, or undefined if none exists.\n */\n protected _lowerByKey(key: K, iterationType: IterationType): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive binary search implementation\n const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {\n if (!this.isRealNode(cur)) return undefined;\n\n const cmp = this.comparator(cur.key!, key);\n\n if (cmp < 0) {\n // Current node satisfies the lower condition (cur.key < target).\n // Try to find a larger candidate in the right subtree.\n const rightResult = dfs(cur.right);\n return rightResult ?? cur;\n } else {\n // Current node is too large or equal, move left to find smaller keys.\n return dfs(cur.left);\n }\n };\n\n return dfs(this.root);\n } else {\n // Iterative binary search implementation\n let current: BSTNode<K, V> | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (this.isRealNode(current)) {\n const cmp = this.comparator(current.key!, key);\n\n if (cmp < 0) {\n // Current node is a candidate. Save it and try right subtree for a larger key.\n result = current;\n current = current.right ?? undefined;\n } else {\n // Current node is too large or equal, move left.\n current = current.left ?? undefined;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) In-order traversal search for lower by predicate.\n * Falls back to linear in-order traversal when predicate-based search is required.\n * Returns the node that satisfies the predicate and appears last in in-order traversal.\n * @remarks Time Complexity: O(n) since it may visit every node.\n * Space Complexity: O(h) for recursion, O(h) for iterative stack.\n *\n * @param predicate - The predicate function to test nodes.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The last node satisfying predicate (highest key < target), or undefined if none found.\n */\n protected _lowerByPredicate(\n predicate: NodePredicate<BSTNode<K, V>>,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive in-order traversal\n let result: BSTNode<K, V> | undefined = undefined;\n\n const dfs = (cur: BSTNode<K, V> | null | undefined): void => {\n if (!this.isRealNode(cur)) return;\n\n // In-order: process left subtree first\n if (this.isRealNode(cur.left)) dfs(cur.left);\n\n // Check current node\n if (predicate(cur)) {\n result = cur;\n }\n\n // Process right subtree\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(this.root);\n return result;\n } else {\n // Iterative in-order traversal using explicit stack\n const stack: (BSTNode<K, V> | null | undefined)[] = [];\n let current: BSTNode<K, V> | null | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (stack.length > 0 || this.isRealNode(current)) {\n if (this.isRealNode(current)) {\n // Go to the leftmost node\n stack.push(current);\n current = current.left;\n } else {\n // Pop from stack and process\n const node = stack.pop();\n if (!this.isRealNode(node)) break;\n\n // Check if current node satisfies predicate\n if (predicate(node)) {\n result = node;\n }\n\n // Visit right subtree\n current = node.right;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) Core bound search implementation supporting all parameter types.\n * Unified logic for both lowerBound and upperBound.\n * Resolves various input types (Key, Node, Entry, Predicate) using parent class utilities.\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param isLower - True for lowerBound (>=), false for upperBound (>).\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first matching node, or undefined if no such node exists.\n */\n protected _bound(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n isLower: boolean,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {\n return undefined;\n }\n\n // Check if input is a predicate function first\n if (this._isPredicate(keyNodeEntryOrPredicate)) {\n return this._boundByPredicate(keyNodeEntryOrPredicate, iterationType);\n }\n\n // Resolve input to a comparable key\n let targetKey: K | undefined;\n\n if (this.isNode(keyNodeEntryOrPredicate)) {\n // Input is a BSTNode - extract its key\n targetKey = keyNodeEntryOrPredicate.key;\n } else if (this.isEntry(keyNodeEntryOrPredicate)) {\n // Input is a [key, value] entry - extract the key\n const key = keyNodeEntryOrPredicate[0];\n if (key === null || key === undefined) {\n return undefined;\n }\n targetKey = key;\n } else {\n // Input is a raw key\n targetKey = keyNodeEntryOrPredicate;\n }\n\n // Execute key-based search with binary search optimization\n if (targetKey !== undefined) {\n return this._boundByKey(targetKey, isLower, iterationType);\n }\n\n return undefined;\n }\n\n /**\n * (Protected) Binary search for bound by key with pruning optimization.\n * Performs standard BST binary search, choosing left or right subtree based on comparator result.\n * For lowerBound: finds first node where key >= target.\n * For upperBound: finds first node where key > target.\n * @param key - The target key to search for.\n * @param isLower - True for lowerBound (>=), false for upperBound (>).\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node matching the bound condition, or undefined if none exists.\n */\n protected _boundByKey(key: K, isLower: boolean, iterationType: IterationType): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive binary search implementation\n const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {\n if (!this.isRealNode(cur)) return undefined;\n\n const cmp = this.comparator(cur.key!, key);\n const condition = isLower ? cmp >= 0 : cmp > 0;\n\n if (condition) {\n // Current node satisfies the bound condition.\n // Try to find a closer (smaller key) candidate in the left subtree.\n const leftResult = dfs(cur.left);\n return leftResult ?? cur;\n } else {\n // Current node does not satisfy the condition.\n // Move right to find larger keys.\n return dfs(cur.right);\n }\n };\n\n return dfs(this.root);\n } else {\n // Iterative binary search implementation\n let current: BSTNode<K, V> | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (this.isRealNode(current)) {\n const cmp = this.comparator(current.key!, key);\n const condition = isLower ? cmp >= 0 : cmp > 0;\n\n if (condition) {\n // Current node is a candidate. Save it and try left subtree for a closer match.\n result = current;\n current = current.left ?? undefined;\n } else {\n // Move right to find larger keys.\n current = current.right ?? undefined;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) In-order traversal search by predicate.\n * Falls back to linear in-order traversal when predicate-based search is required.\n * Returns the first node that satisfies the predicate function.\n * Note: Predicate-based search cannot leverage BST's binary search optimization.\n * Time Complexity: O(n) since it may visit every node.\n * @param predicate - The predicate function to test nodes.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node satisfying predicate, or undefined if none found.\n */\n protected _boundByPredicate(\n predicate: NodePredicate<BSTNode<K, V>>,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive in-order traversal\n let result: BSTNode<K, V> | undefined = undefined;\n\n const dfs = (cur: BSTNode<K, V> | null | undefined): void => {\n if (result || !this.isRealNode(cur)) return;\n\n // In-order: process left subtree first\n if (this.isRealNode(cur.left)) dfs(cur.left);\n\n // Check current node\n if (!result && predicate(cur)) {\n result = cur;\n }\n\n // Process right subtree\n if (!result && this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(this.root);\n return result;\n } else {\n // Iterative in-order traversal using explicit stack\n const stack: (BSTNode<K, V> | null | undefined)[] = [];\n let current: BSTNode<K, V> | null | undefined = this.root;\n\n while (stack.length > 0 || this.isRealNode(current)) {\n if (this.isRealNode(current)) {\n // Go to the leftmost node\n stack.push(current);\n current = current.left;\n } else {\n // Pop from stack and process\n const node = stack.pop();\n if (!this.isRealNode(node)) break;\n\n // Check if current node satisfies predicate\n if (predicate(node)) {\n return node;\n }\n\n // Visit right subtree\n current = node.right;\n }\n }\n\n return undefined;\n }\n }\n\n /**\n * (Protected) Creates a new, empty instance of the same BST constructor.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [options] - Options for the new BST.\n * @returns A new, empty BST.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<BSTOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BSTOptions<TK, TV, TR>\n ) => BST<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Creates a new instance of the same BST constructor, potentially with different generic types.\n * @remarks Time O(N log N) or O(N^2) (from constructor) due to processing the iterable.\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [iter=[]] - An iterable to populate the new BST.\n * @param [options] - Options for the new BST.\n * @returns A new BST.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<BSTOptions<TK, TV, TR>>\n ): BST<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BSTOptions<TK, TV, TR>\n ) => BST<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n /**\n * (Protected) Snapshots the current BST's configuration options.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the options.\n * @returns The options object.\n */\n protected override _snapshotOptions<TK = K, TV = V, TR = R>(): BSTOptions<TK, TV, TR> {\n return {\n ...super._snapshotOptions<TK, TV, TR>(),\n comparator: this._comparator as unknown as BSTOptions<TK, TV, TR>['comparator']\n };\n }\n\n /**\n * (Protected) Converts a key, node, or entry into a standardized [node, value] tuple.\n * @remarks Time O(1)\n *\n * @param keyNodeOrEntry - The input item.\n * @param [value] - An optional value (used if input is just a key).\n * @returns A tuple of [node, value].\n */\n protected override _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): [OptNode<BSTNode<K, V>>, V | undefined] {\n const [node, entryValue] = super._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (node === null) return [undefined, undefined]; // BST handles null differently (as undefined)\n return [node, value ?? entryValue];\n }\n\n /**\n * (Protected) Sets the root node and clears its parent reference.\n * @remarks Time O(1)\n *\n * @param v - The node to set as root.\n */\n protected override _setRoot(v: OptNode<BSTNode<K, V>>) {\n if (v) v.parent = undefined;\n this._root = v;\n }\n\n /**\n * (Protected) Compares two keys using the tree's comparator and reverse setting.\n * @remarks Time O(1) Space O(1)\n *\n * @param a - The first key.\n * @param b - The second key.\n * @returns A number (1, -1, or 0) representing the comparison.\n */\n protected _compare(a: K, b: K) {\n return this._comparator(a, b);\n }\n\n /**\n * (Private) Deletes a node by its key.\n * @remarks Standard BST deletion algorithm. Time O(log N), O(N) worst-case. Space O(1).\n *\n * @param key - The key of the node to delete.\n * @returns True if the node was found and deleted, false otherwise.\n */\n protected _deleteByKey(key: K): boolean {\n let node = this._root as BSTNode<K, V> | undefined;\n\n // 1. Find the node\n while (node) {\n const cmp = this._compare(node.key, key);\n if (cmp === 0) break;\n node = cmp > 0 ? (node.left as BSTNode<K, V> | undefined) : (node.right as BSTNode<K, V> | undefined);\n }\n if (!node) return false; // Not found\n\n // Helper to replace node `u` with node `v`\n const transplant = (u: BSTNode<K, V> | undefined, v: BSTNode<K, V> | undefined) => {\n const p = u?.parent as BSTNode<K, V> | undefined;\n if (!p) {\n this._setRoot(v);\n } else if (p.left === u) {\n p.left = v;\n } else {\n p.right = v;\n }\n if (v) v.parent = p;\n };\n\n // Helper to find the minimum node in a subtree\n const minNode = (x: BSTNode<K, V> | undefined): BSTNode<K, V> | undefined => {\n if (!x) return undefined;\n while (x.left !== undefined && x.left !== null) x = x.left as BSTNode<K, V>;\n return x;\n };\n\n // 2. Perform deletion\n if (node.left === undefined) {\n // Case 1: No left child\n transplant(node, node.right as BSTNode<K, V> | undefined);\n } else if (node.right === undefined) {\n // Case 2: No right child\n transplant(node, node.left as BSTNode<K, V> | undefined);\n } else {\n // Case 3: Two children\n const succ = minNode(node.right as BSTNode<K, V> | undefined)!; // Find successor\n if (succ.parent !== node) {\n transplant(succ, succ.right as BSTNode<K, V> | undefined);\n succ.right = node.right as BSTNode<K, V> | undefined;\n if (succ.right) (succ.right as BSTNode<K, V>).parent = succ;\n }\n transplant(node, succ);\n succ.left = node.left as BSTNode<K, V> | undefined;\n if (succ.left) (succ.left as BSTNode<K, V>).parent = succ;\n }\n\n this._size = Math.max(0, ((this as any)._size ?? 0) - 1);\n return true;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport { getMSB } from '../../utils';\n\n/**\n *\n */\nexport class BinaryIndexedTree {\n protected readonly _freq: number;\n protected readonly _max: number;\n\n /**\n * The constructor initializes the properties of an object, including default frequency, maximum\n * value, a freqMap data structure, the most significant bit, and the count of negative frequencies.\n * @param - - `frequency`: The default frequency value. It is optional and has a default\n * value of 0.\n */\n constructor({ frequency = 0, max }: { frequency?: number; max: number }) {\n this._freq = frequency;\n this._max = max;\n this._freqMap = { 0: 0 };\n this._msb = getMSB(max);\n this._negativeCount = frequency < 0 ? max : 0;\n }\n\n protected _freqMap: Record<number, number>;\n\n /**\n * The function returns the frequency map of numbers.\n * @returns The `_freqMap` property, which is a record with number keys and number values, is being\n * returned.\n */\n get freqMap(): Record<number, number> {\n return this._freqMap;\n }\n\n protected _msb: number;\n\n /**\n * The function returns the value of the _msb property.\n * @returns The `_msb` property of the object.\n */\n get msb(): number {\n return this._msb;\n }\n\n protected _negativeCount: number;\n\n /**\n * The function returns the value of the _negativeCount property.\n * @returns The method is returning the value of the variable `_negativeCount`, which is of type\n * `number`.\n */\n get negativeCount(): number {\n return this._negativeCount;\n }\n\n /**\n * The above function returns the value of the protected variable `_freq`.\n * @returns The frequency value stored in the protected variable `_freq`.\n */\n get freq(): number {\n return this._freq;\n }\n\n /**\n * The above function returns the maximum value.\n * @returns The maximum value stored in the variable `_max`.\n */\n get max(): number {\n return this._max;\n }\n\n /**\n * The function \"readSingle\" reads a single number from a specified index.\n * @param {number} index - The `index` parameter is a number that represents the index of an element in a\n * collection or array.\n * @returns a number.\n */\n readSingle(index: number): number {\n this._checkIndex(index);\n return this._readSingle(index);\n }\n\n /**\n * The \"update\" function updates the value at a given index by adding a delta and triggers a callback\n * to notify of the change.\n * @param {number} position - The `index` parameter represents the index of the element that needs to be\n * updated in the data structure.\n * @param {number} change - The \"delta\" parameter represents the change in value that needs to be\n * applied to the frequency at the specified index.\n */\n update(position: number, change: number): void {\n this._checkIndex(position);\n const freqCur = this._readSingle(position);\n\n this._update(position, change);\n this._updateNegativeCount(freqCur, freqCur + change);\n }\n\n /**\n * The function \"writeSingle\" checks the index and writes a single value with a given frequency.\n * @param {number} index - The `index` parameter is a number that represents the index of an element. It\n * is used to identify the specific element that needs to be written.\n * @param {number} freq - The `freq` parameter represents the frequency value that needs to be\n * written.\n */\n writeSingle(index: number, freq: number): void {\n this._checkIndex(index);\n this._writeSingle(index, freq);\n }\n\n /**\n * The read function takes a count parameter, checks if it is an integer, and returns the result of\n * calling the _read function with the count parameter clamped between 0 and the maximum value.\n * @param {number} count - The `count` parameter is a number that represents the number of items to\n * read.\n * @returns a number.\n */\n read(count: number): number {\n if (!Number.isInteger(count)) {\n throw new Error('Invalid count');\n }\n return this._read(Math.max(Math.min(count, this.max), 0));\n }\n\n /**\n * The function returns the lower bound of a non-descending sequence that sums up to a given number.\n * @param {number} sum - The `sum` parameter is a number that represents the target sum that we want\n * to find in the sequence.\n * @returns The lowerBound function is returning a number.\n */\n lowerBound(sum: number): number {\n if (this.negativeCount > 0) {\n throw new Error('Sequence is not non-descending');\n }\n return this._binarySearch(sum, (x, y) => x < y);\n }\n\n /**\n * The upperBound function returns the index of the first element in a sequence that is greater than\n * or equal to a given sum.\n * @param {number} sum - The \"sum\" parameter is a number that represents the target sum that we want\n * to find in the sequence.\n * @returns The upperBound function is returning a number.\n */\n upperBound(sum: number): number {\n if (this.negativeCount > 0) {\n throw new Error('Must not be descending');\n }\n return this._binarySearch(sum, (x, y) => x <= y);\n }\n\n /**\n * The function calculates the prefix sum of an array using a binary indexed tree.\n * @param {number} i - The parameter \"i\" in the function \"getPrefixSum\" represents the index of the element in the\n * array for which we want to calculate the prefix sum.\n * @returns The function `getPrefixSum` returns the prefix sum of the elements in the binary indexed tree up to index\n * `i`.\n */\n getPrefixSum(i: number): number {\n this._checkIndex(i);\n i++; // Convert to 1-based index\n\n let sum = 0;\n while (i > 0) {\n sum += this._getFrequency(i);\n i -= i & -i;\n }\n\n return sum;\n }\n\n /**\n * The function returns the value of a specific index in a freqMap data structure, or a default value if\n * the index is not found.\n * @param {number} index - The `index` parameter is a number that represents the index of a node in a\n * freqMap data structure.\n * @returns a number.\n */\n protected _getFrequency(index: number): number {\n if (index in this.freqMap) {\n return this.freqMap[index];\n }\n\n return this.freq * (index & -index);\n }\n\n /**\n * The function _updateFrequency adds a delta value to the element at the specified index in the freqMap array.\n * @param {number} index - The index parameter is a number that represents the index of the freqMap\n * element that needs to be updated.\n * @param {number} delta - The `delta` parameter represents the change in value that needs to be\n * added to the freqMap at the specified `index`.\n */\n protected _updateFrequency(index: number, delta: number): void {\n this.freqMap[index] = this._getFrequency(index) + delta;\n }\n\n /**\n * The function checks if the given index is valid and within the range.\n * @param {number} index - The parameter \"index\" is of type number and represents the index value\n * that needs to be checked.\n */\n protected _checkIndex(index: number): void {\n if (!Number.isInteger(index)) {\n throw new Error('Invalid index: Index must be an integer.');\n }\n if (index < 0 || index >= this.max) {\n throw new Error('Index out of range: Index must be within the range [0, this.max).');\n }\n }\n\n /**\n * The function calculates the sum of elements in an array up to a given index using a binary indexed\n * freqMap.\n * @param {number} index - The `index` parameter is a number that represents the index of an element in a\n * data structure.\n * @returns a number.\n */\n protected _readSingle(index: number): number {\n index = index + 1;\n let sum = this._getFrequency(index);\n const z = index - (index & -index);\n\n index--;\n\n while (index !== z) {\n sum -= this._getFrequency(index);\n index -= index & -index;\n }\n\n return sum;\n }\n\n /**\n * The function `_updateNegativeCount` updates a counter based on changes in frequency values.\n * @param {number} freqCur - The current frequency value.\n * @param {number} freqNew - The freqNew parameter represents the new frequency value.\n */\n protected _updateNegativeCount(freqCur: number, freqNew: number): void {\n if (freqCur < 0 && freqNew >= 0) {\n this._negativeCount--;\n } else if (freqCur >= 0 && freqNew < 0) {\n this._negativeCount++;\n }\n }\n\n /**\n * The `_update` function updates the values in a binary indexed freqMap starting from a given index and\n * propagating the changes to its parent nodes.\n * @param {number} index - The `index` parameter is a number that represents the index of the element in\n * the data structure that needs to be updated.\n * @param {number} delta - The `delta` parameter represents the change in value that needs to be\n * applied to the elements in the data structure.\n */\n protected _update(index: number, delta: number): void {\n index = index + 1;\n\n while (index <= this.max) {\n this._updateFrequency(index, delta);\n index += index & -index;\n }\n }\n\n /**\n * The `_writeSingle` function updates the frequency at a specific index and triggers a callback if\n * the frequency has changed.\n * @param {number} index - The `index` parameter is a number that represents the index of the element\n * being modified or accessed.\n * @param {number} freq - The `freq` parameter represents the new frequency value that needs to be\n * written to the specified index `index`.\n */\n protected _writeSingle(index: number, freq: number): void {\n const freqCur = this._readSingle(index);\n\n this._update(index, freq - freqCur);\n this._updateNegativeCount(freqCur, freq);\n }\n\n /**\n * The `_read` function calculates the sum of values in a binary freqMap up to a given count.\n * @param {number} count - The `count` parameter is a number that represents the number of elements\n * to read from the freqMap.\n * @returns the sum of the values obtained from calling the `_getFrequency` method for each index in the\n * range from `count` to 1.\n */\n protected _read(count: number): number {\n let index = count;\n let sum = 0;\n while (index) {\n sum += this._getFrequency(index);\n index -= index & -index;\n }\n\n return sum;\n }\n\n /**\n * The function `_binarySearch` performs a binary search to find the largest number that satisfies a given\n * condition.\n * @param {number} sum - The sum parameter is a number that represents the target sum value.\n * @param before - The `before` parameter is a function that takes two numbers `x` and `y` as\n * arguments and returns a boolean value. It is used to determine if `x` is less than or equal to\n * `y`. The purpose of this function is to compare two numbers and determine their order.\n * @returns the value of the variable \"left\".\n */\n protected _binarySearch(sum: number, before: (x: number, y: number) => boolean): number {\n let left = 0;\n let right = this.msb << 1;\n let sumT = sum;\n\n while (right > left + 1) {\n const middle = (left + right) >> 1;\n const sumM = this._getFrequency(middle);\n\n if (middle <= this.max && before(sumM, sumT)) {\n sumT -= sumM;\n left = middle;\n } else {\n right = middle;\n }\n }\n return left;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { SegmentTreeNodeVal } from '../../types';\n\nexport class SegmentTreeNode {\n /**\n * The constructor initializes the properties of a SegmentTreeNode object.\n * @param {number} start - The `start` parameter represents the starting index of the segment covered\n * by this node in a segment tree.\n * @param {number} end - The `end` parameter represents the end index of the segment covered by this\n * node in a segment tree.\n * @param {number} sum - The `sum` parameter represents the sum of the values in the range covered by\n * the segment tree node.\n * @param {SegmentTreeNodeVal | undefined} [value] - The `value` parameter is an optional parameter\n * of type `SegmentTreeNodeVal`. It represents the value associated with the segment tree node.\n */\n constructor(start: number, end: number, sum: number, value?: SegmentTreeNodeVal | undefined) {\n this._start = start;\n this._end = end;\n this._sum = sum;\n this._value = value || undefined;\n }\n\n protected _start = 0;\n\n /**\n * The function returns the value of the protected variable _start.\n * @returns The start value, which is of type number.\n */\n get start(): number {\n return this._start;\n }\n\n /**\n * The above function sets the value of the \"start\" property.\n * @param {number} value - The value parameter is of type number.\n */\n set start(value: number) {\n this._start = value;\n }\n\n protected _end = 0;\n\n /**\n * The function returns the value of the protected variable `_end`.\n * @returns The value of the protected property `_end`.\n */\n get end(): number {\n return this._end;\n }\n\n /**\n * The above function sets the value of the \"end\" property.\n * @param {number} value - The value parameter is a number that represents the new value for the end\n * property.\n */\n set end(value: number) {\n this._end = value;\n }\n\n protected _value: SegmentTreeNodeVal | undefined = undefined;\n\n /**\n * The function returns the value of a segment tree node.\n * @returns The value being returned is either a `SegmentTreeNodeVal` object or `undefined`.\n */\n get value(): SegmentTreeNodeVal | undefined {\n return this._value;\n }\n\n /**\n * The function sets the value of a segment tree node.\n * @param {SegmentTreeNodeVal | undefined} value - The `value` parameter is of type\n * `SegmentTreeNodeVal` or `undefined`.\n */\n set value(value: SegmentTreeNodeVal | undefined) {\n this._value = value;\n }\n\n protected _sum = 0;\n\n /**\n * The function returns the value of the sum property.\n * @returns The method is returning the value of the variable `_sum`.\n */\n get sum(): number {\n return this._sum;\n }\n\n /**\n * The above function sets the value of the sum property.\n * @param {number} value - The parameter \"value\" is of type \"number\".\n */\n set sum(value: number) {\n this._sum = value;\n }\n\n protected _left: SegmentTreeNode | undefined = undefined;\n\n /**\n * The function returns the left child of a segment tree node.\n * @returns The `left` property of the `SegmentTreeNode` object is being returned. It is of type\n * `SegmentTreeNode` or `undefined`.\n */\n get left(): SegmentTreeNode | undefined {\n return this._left;\n }\n\n /**\n * The function sets the value of the left property of a SegmentTreeNode object.\n * @param {SegmentTreeNode | undefined} value - The value parameter is of type SegmentTreeNode or\n * undefined.\n */\n set left(value: SegmentTreeNode | undefined) {\n this._left = value;\n }\n\n protected _right: SegmentTreeNode | undefined = undefined;\n\n /**\n * The function returns the right child of a segment tree node.\n * @returns The `getRight()` method is returning a value of type `SegmentTreeNode` or `undefined`.\n */\n get right(): SegmentTreeNode | undefined {\n return this._right;\n }\n\n /**\n * The function sets the right child of a segment tree node.\n * @param {SegmentTreeNode | undefined} value - The `value` parameter is of type `SegmentTreeNode |\n * undefined`. This means that it can accept either a `SegmentTreeNode` object or `undefined` as its\n * value.\n */\n set right(value: SegmentTreeNode | undefined) {\n this._right = value;\n }\n}\n\nexport class SegmentTree {\n /**\n * The constructor initializes the values, start, end, and root properties of an object.\n * @param {number[]} values - An array of numbers that will be used to build a binary search tree.\n * @param {number} [start] - The `start` parameter is the index of the first element in the `values` array that should\n * be included in the range. If no value is provided for `start`, it defaults to 0, which means the range starts from\n * the beginning of the array.\n * @param {number} [end] - The \"end\" parameter is the index of the last element in the \"values\" array that should be\n * included in the range. If not provided, it defaults to the index of the last element in the \"values\" array.\n */\n constructor(values: number[], start?: number, end?: number) {\n start = start || 0;\n end = end || values.length - 1;\n this._values = values;\n this._start = start;\n this._end = end;\n\n if (values.length > 0) {\n this._root = this.build(start, end);\n } else {\n this._root = undefined;\n this._values = [];\n }\n }\n\n protected _values: number[] = [];\n\n /**\n * The function returns an array of numbers.\n * @returns An array of numbers is being returned.\n */\n get values(): number[] {\n return this._values;\n }\n\n protected _start = 0;\n\n /**\n * The function returns the value of the protected variable _start.\n * @returns The start value, which is of type number.\n */\n get start(): number {\n return this._start;\n }\n\n protected _end: number;\n\n /**\n * The function returns the value of the protected variable `_end`.\n * @returns The value of the protected property `_end`.\n */\n get end(): number {\n return this._end;\n }\n\n protected _root: SegmentTreeNode | undefined;\n\n /**\n * The function returns the root node of a segment tree.\n * @returns The `root` property of the class `SegmentTreeNode` or `undefined` if it is not defined.\n */\n get root(): SegmentTreeNode | undefined {\n return this._root;\n }\n\n /**\n * The build function creates a segment tree by recursively dividing the given range into smaller segments and assigning\n * the sum of values to each segment.\n * @param {number} start - The `start` parameter represents the starting index of the segment or range for which we are\n * building the segment tree.\n * @param {number} end - The \"end\" parameter represents the ending index of the segment or range for which we want to\n * build a segment tree.\n * @returns a SegmentTreeNode object.\n */\n build(start: number, end: number): SegmentTreeNode {\n if (start > end) {\n return new SegmentTreeNode(start, end, 0);\n }\n if (start === end) return new SegmentTreeNode(start, end, this._values[start]);\n\n const mid = start + Math.floor((end - start) / 2);\n const left = this.build(start, mid);\n const right = this.build(mid + 1, end);\n const cur = new SegmentTreeNode(start, end, left.sum + right.sum);\n cur.left = left;\n cur.right = right;\n return cur;\n }\n\n /**\n * The function updates the value of a node in a segment tree and recalculates the sum of its children if they exist.\n * @param {number} index - The index parameter represents the index of the node in the segment tree that needs to be\n * updated.\n * @param {number} sum - The `sum` parameter represents the new value that should be assigned to the `sum` property of\n * the `SegmentTreeNode` at the specified `index`.\n * @param {SegmentTreeNodeVal} [value] - The `value` parameter is an optional value that can be assigned to the `value`\n * property of the `SegmentTreeNode` object. It is not currently used in the code, but you can uncomment the line `//\n * cur.value = value;` and pass a value for `value` in the\n * @returns The function does not return anything.\n */\n updateNode(index: number, sum: number, value?: SegmentTreeNodeVal) {\n const root = this.root || undefined;\n if (!root) {\n return;\n }\n const dfs = (cur: SegmentTreeNode, index: number, sum: number, value?: SegmentTreeNodeVal) => {\n if (cur.start === cur.end && cur.start === index) {\n cur.sum = sum;\n if (value !== undefined) cur.value = value;\n return;\n }\n const mid = cur.start + Math.floor((cur.end - cur.start) / 2);\n if (index <= mid) {\n if (cur.left) {\n dfs(cur.left, index, sum, value);\n }\n } else {\n if (cur.right) {\n dfs(cur.right, index, sum, value);\n }\n }\n if (cur.left && cur.right) {\n cur.sum = cur.left.sum + cur.right.sum;\n }\n };\n\n dfs(root, index, sum, value);\n }\n\n /**\n * The function `querySumByRange` calculates the sum of values within a given range in a segment tree.\n * @param {number} indexA - The starting index of the range for which you want to calculate the sum.\n * @param {number} indexB - The parameter `indexB` represents the ending index of the range for which you want to\n * calculate the sum.\n * @returns The function `querySumByRange` returns a number.\n */\n querySumByRange(indexA: number, indexB: number): number {\n const root = this.root || undefined;\n if (!root) {\n return 0;\n }\n\n if (indexA < 0 || indexB >= this.values.length || indexA > indexB) {\n return NaN;\n }\n\n const dfs = (cur: SegmentTreeNode, i: number, j: number): number => {\n if (i <= cur.start && j >= cur.end) {\n // The range [i, j] completely covers the current node's range [cur.start, cur.end]\n return cur.sum;\n }\n const mid = cur.start + Math.floor((cur.end - cur.start) / 2);\n if (j <= mid) {\n if (cur.left) {\n return dfs(cur.left, i, j);\n } else {\n return NaN;\n }\n } else if (i > mid) {\n if (cur.right) {\n return dfs(cur.right, i, j);\n } else {\n return NaN;\n }\n } else {\n // Query both left and right subtrees\n let leftSum = 0;\n let rightSum = 0;\n if (cur.left) {\n leftSum = dfs(cur.left, i, mid);\n }\n if (cur.right) {\n rightSum = dfs(cur.right, mid + 1, j);\n }\n return leftSum + rightSum;\n }\n };\n return dfs(root, indexA, indexB);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport { BST } from './bst';\nimport type {\n AVLTreeOptions,\n BinaryTreeDeleteResult,\n BinaryTreeOptions,\n BSTNOptKeyOrNode,\n EntryCallback,\n FamilyPosition,\n IterationType,\n RBTNColor\n} from '../../types';\nimport { IBinaryTree } from '../../interfaces';\n\n/**\n * Represents a Node in an AVL (Adelson-Velsky and Landis) Tree.\n * It extends a BSTNode and ensures the 'height' property is maintained.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n */\nexport class AVLTreeNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: AVLTreeNode<K, V> = undefined;\n\n /**\n * Creates an instance of AVLTreeNode.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key of the node.\n * @param [value] - The value associated with the key.\n */\n constructor(key: K, value?: V) {\n this.key = key;\n this.value = value;\n }\n\n _left?: AVLTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the left child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The left child.\n */\n get left(): AVLTreeNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Sets the left child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the left child.\n */\n set left(v: AVLTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: AVLTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the right child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The right child.\n */\n get right(): AVLTreeNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Sets the right child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the right child.\n */\n set right(v: AVLTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Represents a self-balancing AVL (Adelson-Velsky and Landis) Tree.\n * This tree extends BST and performs rotations on add/delete to maintain balance.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n * @template R - The type of the raw data object (if using `toEntryFn`).\n *\n * 1. Height-Balanced: Each node's left and right subtrees differ in height by no more than one.\n * 2. Automatic Rebalancing: AVL trees rebalance themselves automatically during insertions and deletions.\n * 3. Rotations for Balancing: Utilizes rotations (single or double) to maintain balance after updates.\n * 4. Order Preservation: Maintains the binary search tree property where left child values are less than the parent, and right child values are greater.\n * 5. Efficient Lookups: Offers O(log n) search time, where 'n' is the number of nodes, due to its balanced nature.\n * 6. Complex Insertions and Deletions: Due to rebalancing, these operations are more complex than in a regular BST.\n * 7. Path Length: The path length from the root to any leaf is longer compared to an unbalanced BST, but shorter than a linear chain of nodes.\n *\n * @example\n * // basic AVLTree creation and add operation\n * // Create a simple AVLTree with initial values\n * const tree = new AVLTree([5, 2, 8, 1, 9]);\n *\n * tree.print();\n * // _2___\n * // / \\\n * // 1 _8_\n * // / \\\n * // 5 9\n *\n * // Verify the tree maintains sorted order\n * console.log([...tree.keys()]); // [1, 2, 5, 8, 9];\n *\n * // Check size\n * console.log(tree.size); // 5;\n *\n * // Add a new element\n * tree.add(3);\n * console.log(tree.size); // 6;\n * console.log([...tree.keys()]); // [1, 2, 3, 5, 8, 9];\n * @example\n * // AVLTree has and get operations\n * const tree = new AVLTree<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * // Check if element exists\n * console.log(tree.has(6)); // true;\n * console.log(tree.has(99)); // false;\n *\n * // Get node by key\n * const node = tree.getNode(6);\n * console.log(node?.key); // 6;\n *\n * // Verify tree is balanced\n * console.log(tree.isAVLBalanced()); // true;\n * @example\n * // AVLTree delete and balance verification\n * const tree = new AVLTree([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * // Delete an element\n * tree.delete(10);\n * console.log(tree.has(10)); // false;\n *\n * // Tree should remain balanced after deletion\n * console.log(tree.isAVLBalanced()); // true;\n *\n * // Size decreased\n * console.log(tree.size); // 15;\n *\n * // Remaining elements are still sorted\n * const keys = [...tree.keys()];\n * console.log(keys); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16];\n * @example\n * // AVLTree for university ranking system with strict balance\n * interface University {\n * name: string;\n * rank: number;\n * students: number;\n * }\n *\n * // AVLTree provides highest search efficiency with strict balance\n * // (every node's left/right subtrees differ by at most 1 in height)\n * const universityTree = new AVLTree<number, University>([\n * [1, { name: 'MIT', rank: 1, students: 1200 }],\n * [5, { name: 'Stanford', rank: 5, students: 1800 }],\n * [3, { name: 'Harvard', rank: 3, students: 2300 }],\n * [2, { name: 'Caltech', rank: 2, students: 400 }],\n * [4, { name: 'CMU', rank: 4, students: 1500 }]\n * ]);\n *\n * // Quick lookup by rank\n * const mit = universityTree.get(1);\n * console.log(mit?.name); // 'MIT';\n *\n * const cmulevel = universityTree.getHeight(4);\n * console.log(typeof cmulevel); // 'number';\n *\n * // Tree maintains strict balance during insertions and deletions\n * console.log(universityTree.isAVLBalanced()); // true;\n *\n * // Add more universities\n * universityTree.add(6, { name: 'Oxford', rank: 6, students: 2000 });\n * console.log(universityTree.isAVLBalanced()); // true;\n *\n * // Delete and verify balance is maintained\n * universityTree.delete(2);\n * console.log(universityTree.has(2)); // false;\n * console.log(universityTree.isAVLBalanced()); // true;\n *\n * // Get all remaining universities in rank order\n * const remainingRanks = [...universityTree.keys()];\n * console.log(remainingRanks); // [1, 3, 4, 5, 6];\n * console.log(universityTree.size); // 5;\n * @example\n * // Find elements in a range\n * // In interval queries, AVL trees, with their strictly balanced structure and lower height, offer better query efficiency, making them ideal for frequent and high-performance interval queries. In contrast, Red-Black trees, with lower update costs, are more suitable for scenarios involving frequent insertions and deletions where the requirements for interval queries are less demanding.\n * type Datum = { timestamp: Date; temperature: number };\n * // Fixed dataset of CPU temperature readings\n * const cpuData: Datum[] = [\n * { timestamp: new Date('2024-12-02T00:00:00'), temperature: 55.1 },\n * { timestamp: new Date('2024-12-02T00:01:00'), temperature: 56.3 },\n * { timestamp: new Date('2024-12-02T00:02:00'), temperature: 54.8 },\n * { timestamp: new Date('2024-12-02T00:03:00'), temperature: 57.2 },\n * { timestamp: new Date('2024-12-02T00:04:00'), temperature: 58.0 },\n * { timestamp: new Date('2024-12-02T00:05:00'), temperature: 59.4 },\n * { timestamp: new Date('2024-12-02T00:06:00'), temperature: 60.1 },\n * { timestamp: new Date('2024-12-02T00:07:00'), temperature: 61.3 },\n * { timestamp: new Date('2024-12-02T00:08:00'), temperature: 62.0 },\n * { timestamp: new Date('2024-12-02T00:09:00'), temperature: 63.5 },\n * { timestamp: new Date('2024-12-02T00:10:00'), temperature: 64.0 },\n * { timestamp: new Date('2024-12-02T00:11:00'), temperature: 62.8 },\n * { timestamp: new Date('2024-12-02T00:12:00'), temperature: 61.5 },\n * { timestamp: new Date('2024-12-02T00:13:00'), temperature: 60.2 },\n * { timestamp: new Date('2024-12-02T00:14:00'), temperature: 59.8 },\n * { timestamp: new Date('2024-12-02T00:15:00'), temperature: 58.6 },\n * { timestamp: new Date('2024-12-02T00:16:00'), temperature: 57.4 },\n * { timestamp: new Date('2024-12-02T00:17:00'), temperature: 56.2 },\n * { timestamp: new Date('2024-12-02T00:18:00'), temperature: 55.7 },\n * { timestamp: new Date('2024-12-02T00:19:00'), temperature: 54.5 },\n * { timestamp: new Date('2024-12-02T00:20:00'), temperature: 53.2 },\n * { timestamp: new Date('2024-12-02T00:21:00'), temperature: 52.8 },\n * { timestamp: new Date('2024-12-02T00:22:00'), temperature: 51.9 },\n * { timestamp: new Date('2024-12-02T00:23:00'), temperature: 50.5 },\n * { timestamp: new Date('2024-12-02T00:24:00'), temperature: 49.8 },\n * { timestamp: new Date('2024-12-02T00:25:00'), temperature: 48.7 },\n * { timestamp: new Date('2024-12-02T00:26:00'), temperature: 47.5 },\n * { timestamp: new Date('2024-12-02T00:27:00'), temperature: 46.3 },\n * { timestamp: new Date('2024-12-02T00:28:00'), temperature: 45.9 },\n * { timestamp: new Date('2024-12-02T00:29:00'), temperature: 45.0 }\n * ];\n *\n * // Create an AVL tree to store CPU temperature data\n * const cpuTemperatureTree = new AVLTree<Date, number, Datum>(cpuData, {\n * toEntryFn: ({ timestamp, temperature }) => [timestamp, temperature]\n * });\n *\n * // Query a specific time range (e.g., from 00:05 to 00:15)\n * const rangeStart = new Date('2024-12-02T00:05:00');\n * const rangeEnd = new Date('2024-12-02T00:15:00');\n * const rangeResults = cpuTemperatureTree.rangeSearch([rangeStart, rangeEnd], node => ({\n * minute: node ? node.key.getMinutes() : 0,\n * temperature: cpuTemperatureTree.get(node ? node.key : undefined)\n * }));\n *\n * console.log(rangeResults); // [\n * // { minute: 5, temperature: 59.4 },\n * // { minute: 6, temperature: 60.1 },\n * // { minute: 7, temperature: 61.3 },\n * // { minute: 8, temperature: 62 },\n * // { minute: 9, temperature: 63.5 },\n * // { minute: 10, temperature: 64 },\n * // { minute: 11, temperature: 62.8 },\n * // { minute: 12, temperature: 61.5 },\n * // { minute: 13, temperature: 60.2 },\n * // { minute: 14, temperature: 59.8 },\n * // { minute: 15, temperature: 58.6 }\n * // ];\n */\nexport class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Creates an instance of AVLTree.\n * @remarks Time O(N log N) (from `addMany` with balanced add). Space O(N).\n *\n * @param [keysNodesEntriesOrRaws=[]] - An iterable of items to add.\n * @param [options] - Configuration options for the AVL tree.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: AVLTreeOptions<K, V, R>\n ) {\n super([], options);\n // Note: super.addMany is called, which in BST defaults to balanced add.\n if (keysNodesEntriesOrRaws) super.addMany(keysNodesEntriesOrRaws);\n }\n\n /**\n * (Protected) Creates a new AVL tree node.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key for the new node.\n * @param [value] - The value for the new node.\n * @returns The newly created AVLTreeNode.\n */\n override createNode(key: K, value?: V): AVLTreeNode<K, V> {\n return new AVLTreeNode<K, V>(key, this._isMapMode ? undefined : value) as AVLTreeNode<K, V>;\n }\n\n /**\n * Checks if the given item is an `AVLTreeNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's an AVLTreeNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is AVLTreeNode<K, V> {\n return keyNodeOrEntry instanceof AVLTreeNode;\n }\n\n /**\n * Adds a new node to the AVL tree and balances the tree path.\n * @remarks Time O(log N) (O(H) for BST add + O(H) for `_balancePath`). Space O(H) for path/recursion.\n *\n * @param keyNodeOrEntry - The key, node, or entry to add.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n override add(\n keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n if (keyNodeOrEntry === null) return false;\n const inserted = super.add(keyNodeOrEntry, value);\n // If insertion was successful, balance the path from the new node up to the root.\n if (inserted) this._balancePath(keyNodeOrEntry);\n return inserted;\n }\n\n /**\n * Deletes a node from the AVL tree and re-balances the tree.\n * @remarks Time O(log N) (O(H) for BST delete + O(H) for `_balancePath`). Space O(H) for path/recursion.\n *\n * @param keyNodeOrEntry - The node to delete.\n * @returns An array containing deletion results.\n */\n override delete(\n keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeDeleteResult<AVLTreeNode<K, V>>[] {\n const deletedResults = super.delete(keyNodeOrEntry);\n // After deletion, balance the path from the parent of the *physically deleted* node.\n for (const { needBalanced } of deletedResults) {\n if (needBalanced) {\n this._balancePath(needBalanced);\n }\n }\n return deletedResults;\n }\n\n /**\n * Rebuilds the tree to be perfectly balanced.\n * @remarks AVL trees are already height-balanced, but this makes them *perfectly* balanced (minimal height and all leaves at N or N-1).\n * Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.\n *\n * @param [iterationType=this.iterationType] - The traversal method for the initial node export.\n * @returns True if successful, false if the tree was empty.\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n === 0) return false;\n\n this._clearNodes();\n\n // Build balanced tree from sorted array\n const build = (l: number, r: number, parent?: AVLTreeNode<K, V>): AVLTreeNode<K, V> | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m]!;\n root.left = build(l, m - 1, root);\n root.right = build(m + 1, r, root);\n root.parent = parent;\n\n // Update height during the build\n const lh = root.left ? (root.left as AVLTreeNode<K, V>).height : -1;\n const rh = root.right ? (root.right as AVLTreeNode<K, V>).height : -1;\n root.height = Math.max(lh, rh) + 1;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n return true;\n }\n\n /**\n * Creates a new AVLTree by mapping each [key, value] pair.\n * @remarks Time O(N log N) (O(N) iteration + O(log M) `add` for each item into the new tree). Space O(N) for the new tree.\n *\n * @template MK - New key type.\n * @template MV - New value type.\n * @template MR - New raw type.\n * @param callback - A function to map each [key, value] pair.\n * @param [options] - Options for the new AVLTree.\n * @param [thisArg] - `this` context for the callback.\n * @returns A new, mapped AVLTree.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<BinaryTreeOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n // Iterates in-order\n for (const [key, value] of this) {\n // `add` on the new tree will be O(log N) and will self-balance.\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * (Protected) Creates a new, empty instance of the same AVLTree constructor.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [options] - Options for the new tree.\n * @returns A new, empty tree.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<AVLTreeOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeOptions<TK, TV, TR>\n ) => this;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Creates a new instance of the same AVLTree constructor, potentially with different generic types.\n * @remarks Time O(N log N) (from constructor) due to processing the iterable.\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [iter=[]] - An iterable to populate the new tree.\n * @param [options] - Options for the new tree.\n * @returns A new AVLTree.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<AVLTreeOptions<TK, TV, TR>>\n ): AVLTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeOptions<TK, TV, TR>\n ) => AVLTree<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n /**\n * (Protected) Swaps properties of two nodes, including height.\n * @remarks Time O(H) (due to `ensureNode`), but O(1) if nodes are passed directly.\n *\n * @param srcNode - The source node.\n * @param destNode - The destination node.\n * @returns The `destNode` (now holding `srcNode`'s properties).\n */\n protected override _swapProperties(\n srcNode: BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>,\n destNode: BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>\n ): AVLTreeNode<K, V> | undefined {\n const srcNodeEnsured = this.ensureNode(srcNode);\n const destNodeEnsured = this.ensureNode(destNode);\n\n if (srcNodeEnsured && destNodeEnsured) {\n const { key, value, height } = destNodeEnsured;\n const tempNode = this.createNode(key, value);\n\n if (tempNode) {\n tempNode.height = height;\n\n // Copy src to dest\n destNodeEnsured.key = srcNodeEnsured.key;\n if (!this._isMapMode) destNodeEnsured.value = srcNodeEnsured.value;\n destNodeEnsured.height = srcNodeEnsured.height;\n\n // Copy temp (original dest) to src\n srcNodeEnsured.key = tempNode.key;\n if (!this._isMapMode) srcNodeEnsured.value = tempNode.value;\n srcNodeEnsured.height = tempNode.height;\n }\n\n return destNodeEnsured;\n }\n return undefined;\n }\n\n /**\n * (Protected) Calculates the balance factor (height(right) - height(left)).\n * @remarks Time O(1) (assumes heights are stored).\n *\n * @param node - The node to check.\n * @returns The balance factor (positive if right-heavy, negative if left-heavy).\n */\n protected _balanceFactor(node: AVLTreeNode<K, V>): number {\n const left = node.left ? (node.left as AVLTreeNode<K, V>).height : -1;\n const right = node.right ? (node.right as AVLTreeNode<K, V>).height : -1;\n return right - left;\n }\n\n /**\n * (Protected) Recalculates and updates the height of a node based on its children's heights.\n * @remarks Time O(1) (assumes children's heights are correct).\n *\n * @param node - The node to update.\n */\n protected _updateHeight(node: AVLTreeNode<K, V>): void {\n const leftHeight = node.left ? (node.left as AVLTreeNode<K, V>).height : -1;\n const rightHeight = node.right ? (node.right as AVLTreeNode<K, V>).height : -1;\n node.height = 1 + Math.max(leftHeight, rightHeight);\n }\n\n /**\n * (Protected) Performs a Left-Left (LL) rotation (a single right rotation).\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceLL(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.left; // The left child\n if (B !== null) A.parent = B;\n if (B && B.right) {\n B.right.parent = A;\n }\n if (B) B.parent = parentOfA;\n\n // Update parent's child pointer\n if (A === this.root) {\n if (B) this._setRoot(B);\n } else {\n if (parentOfA?.left === A) {\n parentOfA.left = B;\n } else {\n if (parentOfA) parentOfA.right = B;\n }\n }\n\n // Perform rotation\n if (B) {\n A.left = B.right;\n B.right = A;\n }\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n }\n\n /**\n * (Protected) Performs a Left-Right (LR) double rotation.\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceLR(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.left;\n let C = undefined;\n if (B) {\n C = B.right; // The \"middle\" node\n }\n if (A && C !== null) A.parent = C;\n if (B && C !== null) B.parent = C;\n\n if (C) {\n if (C.left) {\n if (B !== null) C.left.parent = B;\n }\n if (C.right) {\n C.right.parent = A;\n }\n C.parent = parentOfA;\n }\n\n // Update parent's child pointer\n if (A === this.root) {\n if (C) this._setRoot(C);\n } else {\n if (parentOfA) {\n if (parentOfA.left === A) {\n parentOfA.left = C;\n } else {\n parentOfA.right = C;\n }\n }\n }\n\n // Perform rotation\n if (C) {\n A.left = C.right;\n if (B) B.right = C.left;\n C.left = B;\n C.right = A;\n }\n\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n if (C) this._updateHeight(C);\n }\n\n /**\n * (Protected) Performs a Right-Right (RR) rotation (a single left rotation).\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceRR(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.right; // The right child\n if (B !== null) A.parent = B;\n if (B) {\n if (B.left) {\n B.left.parent = A;\n }\n B.parent = parentOfA;\n }\n\n // Update parent's child pointer\n if (A === this.root) {\n if (B) this._setRoot(B);\n } else {\n if (parentOfA) {\n if (parentOfA.left === A) {\n parentOfA.left = B;\n } else {\n parentOfA.right = B;\n }\n }\n }\n\n // Perform rotation\n if (B) {\n A.right = B.left;\n B.left = A;\n }\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n }\n\n /**\n * (Protected) Performs a Right-Left (RL) double rotation.\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceRL(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.right;\n let C = undefined;\n if (B) {\n C = B.left; // The \"middle\" node\n }\n\n if (C !== null) A.parent = C;\n if (B && C !== null) B.parent = C;\n\n if (C) {\n if (C.left) {\n C.left.parent = A;\n }\n if (C.right) {\n if (B !== null) C.right.parent = B;\n }\n C.parent = parentOfA;\n }\n\n // Update parent's child pointer\n if (A === this.root) {\n if (C) this._setRoot(C);\n } else {\n if (parentOfA) {\n if (parentOfA.left === A) {\n parentOfA.left = C;\n } else {\n parentOfA.right = C;\n }\n }\n }\n\n // Perform rotation\n if (C) A.right = C.left;\n if (B && C) B.left = C.right;\n if (C) C.left = A;\n if (C) C.right = B;\n\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n if (C) this._updateHeight(C);\n }\n\n /**\n * (Protected) Traverses up the tree from the specified node, updating heights and performing rotations as needed.\n * @remarks Time O(log N) (O(H)), as it traverses the path to root. Space O(H) for the path array.\n *\n * @param node - The node to start balancing from (e.g., the newly inserted node or parent of the deleted node).\n */\n protected _balancePath(node: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined): void {\n // Get the path from the node to the root.\n node = this.ensureNode(node);\n const path = this.getPathToRoot(node, node => node, false);\n\n // Iterate up the path (from node to root)\n for (let i = 0; i < path.length; i++) {\n const A = path[i];\n if (A) {\n this._updateHeight(A);\n\n // Check the balance factor\n switch (this._balanceFactor(A)) {\n case -2: // Left-heavy\n if (A && A.left) {\n if (this._balanceFactor(A.left) <= 0) {\n // Left-Left case\n this._balanceLL(A);\n } else {\n // Left-Right case\n this._balanceLR(A);\n }\n }\n break;\n case +2: // Right-heavy\n if (A && A.right) {\n if (this._balanceFactor(A.right) >= 0) {\n // Right-Right case\n this._balanceRR(A);\n } else {\n // Right-Left case\n this._balanceRL(A);\n }\n }\n }\n }\n }\n }\n\n /**\n * (Protected) Replaces a node, ensuring height is copied.\n * @remarks Time O(1)\n *\n * @param oldNode - The node to be replaced.\n * @param newNode - The node to insert.\n * @returns The `newNode`.\n */\n protected override _replaceNode(oldNode: AVLTreeNode<K, V>, newNode: AVLTreeNode<K, V>): AVLTreeNode<K, V> {\n // When replacing a node (e.g., on duplicate key), preserve the height.\n newNode.height = oldNode.height;\n return super._replaceNode(oldNode, newNode);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n CRUD,\n EntryCallback,\n FamilyPosition,\n OptNode,\n RBTNColor,\n RedBlackTreeOptions\n} from '../../types';\nimport { BST } from './bst';\nimport { IBinaryTree } from '../../interfaces';\n\nexport class RedBlackTreeNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: RedBlackTreeNode<K, V> = undefined;\n\n /**\n * Create a Red-Black Tree and optionally bulk-insert items.\n * @remarks Time O(n log n), Space O(n)\n * @param key - See parameter type for details.\n * @param [value]- See parameter type for details.\n * @param color - See parameter type for details.\n * @returns New RedBlackTree instance.\n */\n\n constructor(key: K, value?: V, color: RBTNColor = 'BLACK') {\n this.key = key;\n this.value = value;\n this.color = color;\n }\n\n _left?: RedBlackTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n\n get left(): RedBlackTreeNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left node, or null/undefined.\n * @returns void\n */\n\n set left(v: RedBlackTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: RedBlackTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n\n get right(): RedBlackTreeNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right node, or null/undefined.\n * @returns void\n */\n\n set right(v: RedBlackTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Represents a Red-Black Tree (self-balancing BST) supporting map-like mode and stable O(log n) updates.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n * 1. Efficient self-balancing, but not completely balanced. Compared with AVLTree, the addition and deletion efficiency is high, but the query efficiency is slightly lower.\n * 2. It is BST itself. Compared with Heap which is not completely ordered, RedBlackTree is completely ordered.\n *\n * @example\n * // basic Red-Black Tree with simple number keys\n * // Create a simple Red-Black Tree with numeric keys\n * const tree = new RedBlackTree([5, 2, 8, 1, 9]);\n *\n * tree.print();\n * // _2___\n * // / \\\n * // 1 _8_\n * // / \\\n * // 5 9\n *\n * // Verify the tree maintains sorted order\n * console.log([...tree.keys()]); // [1, 2, 5, 8, 9];\n *\n * // Check size\n * console.log(tree.size); // 5;\n * @example\n * // Red-Black Tree with key-value pairs for lookups\n * interface Employee {\n * id: number;\n * name: string;\n * }\n *\n * // Create tree with employee data\n * const employees = new RedBlackTree<number, Employee>([\n * [1, { id: 1, name: 'Alice' }],\n * [3, { id: 3, name: 'Charlie' }],\n * [2, { id: 2, name: 'Bob' }]\n * ]);\n *\n * // Retrieve employee by ID\n * const alice = employees.get(1);\n * console.log(alice?.name); // 'Alice';\n *\n * // Verify sorted order by ID\n * console.log([...employees.keys()]); // [1, 2, 3];\n * @example\n * // Red-Black Tree range search for filtering\n * interface Product {\n * name: string;\n * price: number;\n * }\n *\n * const products = new RedBlackTree<number, Product>([\n * [10, { name: 'Item A', price: 10 }],\n * [25, { name: 'Item B', price: 25 }],\n * [40, { name: 'Item C', price: 40 }],\n * [50, { name: 'Item D', price: 50 }]\n * ]);\n *\n * // Find products in price range [20, 45]\n * const pricesInRange = products.rangeSearch([20, 45], node => {\n * return products.get(node)?.name;\n * });\n *\n * console.log(pricesInRange); // ['Item B', 'Item C'];\n * @example\n * // Red-Black Tree as database index for stock market data\n * interface StockPrice {\n * symbol: string;\n * volume: number;\n * timestamp: Date;\n * }\n *\n * // Simulate real-time stock price index\n * const priceIndex = new RedBlackTree<number, StockPrice>([\n * [142.5, { symbol: 'AAPL', volume: 1000000, timestamp: new Date() }],\n * [335.2, { symbol: 'MSFT', volume: 800000, timestamp: new Date() }],\n * [3285.04, { symbol: 'AMZN', volume: 500000, timestamp: new Date() }],\n * [267.98, { symbol: 'META', volume: 750000, timestamp: new Date() }],\n * [234.57, { symbol: 'GOOGL', volume: 900000, timestamp: new Date() }]\n * ]);\n *\n * // Find highest-priced stock\n * const maxPrice = priceIndex.getRightMost();\n * console.log(priceIndex.get(maxPrice)?.symbol); // 'AMZN';\n *\n * // Find stocks in price range [200, 400] for portfolio balancing\n * const stocksInRange = priceIndex.rangeSearch([200, 400], node => {\n * const stock = priceIndex.get(node);\n * return {\n * symbol: stock?.symbol,\n * price: node,\n * volume: stock?.volume\n * };\n * });\n *\n * console.log(stocksInRange.length); // 3;\n * console.log(stocksInRange.some((s: any) => s.symbol === 'GOOGL')); // true;\n * console.log(stocksInRange.some((s: any) => s.symbol === 'META')); // true;\n * console.log(stocksInRange.some((s: any) => s.symbol === 'MSFT')); // true;\n */\n\nexport class RedBlackTree<K = any, V = any, R = any> extends BST<K, V, R> implements IBinaryTree<K, V, R> {\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: RedBlackTreeOptions<K, V, R>\n ) {\n super([], options);\n\n this._root = this.NIL;\n\n if (keysNodesEntriesOrRaws) {\n this.addMany(keysNodesEntriesOrRaws);\n }\n }\n\n protected override _root: RedBlackTreeNode<K, V> | undefined;\n\n /**\n * Get the current root node.\n * @remarks Time O(1), Space O(1)\n * @returns Root node, or undefined.\n */\n override get root(): RedBlackTreeNode<K, V> | undefined {\n return this._root;\n }\n\n /**\n * Create a red-black node for the given key/value (value ignored in map mode).\n * @remarks Time O(1), Space O(1)\n * @param key - See parameter type for details.\n * @param [value] - See parameter type for details.\n * @param color - See parameter type for details.\n * @returns A new RedBlackTreeNode instance.\n */\n override createNode(key: K, value?: V, color: RBTNColor = 'BLACK'): RedBlackTreeNode<K, V> {\n return new RedBlackTreeNode<K, V>(key, this._isMapMode ? undefined : value, color);\n }\n\n /**\n * Type guard: check whether the input is a RedBlackTreeNode.\n * @remarks Time O(1), Space O(1)\n * @param keyNodeOrEntry - See parameter type for details.\n * @returns True if the value is a RedBlackTreeNode.\n */\n\n override isNode(\n keyNodeOrEntry: K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is RedBlackTreeNode<K, V> {\n return keyNodeOrEntry instanceof RedBlackTreeNode;\n }\n\n /**\n * Remove all nodes and clear the key→value store (if in map mode).\n * @remarks Time O(n), Space O(1)\n * @returns void\n */\n\n override clear() {\n super.clear();\n this._root = this.NIL;\n }\n\n /**\n * Insert or replace an entry using BST order and red-black fix-up.\n * @remarks Time O(log n), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.\n * @param [value]- See parameter type for details.\n * @returns True if inserted or updated; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (!this.isRealNode(newNode)) return false;\n\n const insertStatus = this._insert(newNode);\n\n if (insertStatus === 'CREATED') {\n if (this.isRealNode(this._root)) {\n this._root.color = 'BLACK';\n } else {\n return false;\n }\n if (this._isMapMode) this._setValue(newNode.key, newValue);\n this._size++;\n return true;\n }\n if (insertStatus === 'UPDATED') {\n if (this._isMapMode) this._setValue(newNode.key, newValue);\n return true;\n }\n return false;\n }\n\n /**\n * Delete a node by key/node/entry and rebalance as needed.\n * @remarks Time O(log n), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node to delete.\n * @returns Array with deletion metadata (removed node, rebalancing hint if any).\n */\n\n override delete(\n keyNodeOrEntry: K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>[] {\n if (keyNodeOrEntry === null) return [];\n\n const results: BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>[] = [];\n let nodeToDelete: OptNode<RedBlackTreeNode<K, V>>;\n if (this._isPredicate(keyNodeOrEntry)) nodeToDelete = this.getNode(keyNodeOrEntry);\n else nodeToDelete = this.isRealNode(keyNodeOrEntry) ? keyNodeOrEntry : this.getNode(keyNodeOrEntry);\n\n if (!nodeToDelete) {\n return results;\n }\n\n let originalColor = nodeToDelete.color;\n let replacementNode: RedBlackTreeNode<K, V> | undefined;\n\n if (!this.isRealNode(nodeToDelete.left)) {\n if (nodeToDelete.right !== null) {\n replacementNode = nodeToDelete.right;\n this._transplant(nodeToDelete, nodeToDelete.right);\n }\n } else if (!this.isRealNode(nodeToDelete.right)) {\n replacementNode = nodeToDelete.left;\n this._transplant(nodeToDelete, nodeToDelete.left);\n } else {\n const successor = this.getLeftMost(node => node, nodeToDelete.right);\n if (successor) {\n originalColor = successor.color;\n if (successor.right !== null) replacementNode = successor.right;\n\n if (successor.parent === nodeToDelete) {\n if (this.isRealNode(replacementNode)) {\n replacementNode.parent = successor;\n }\n } else {\n if (successor.right !== null) {\n this._transplant(successor, successor.right);\n successor.right = nodeToDelete.right;\n }\n if (this.isRealNode(successor.right)) {\n successor.right.parent = successor;\n }\n }\n\n this._transplant(nodeToDelete, successor);\n successor.left = nodeToDelete.left;\n if (this.isRealNode(successor.left)) {\n successor.left.parent = successor;\n }\n successor.color = nodeToDelete.color;\n }\n }\n if (this._isMapMode) this._store.delete(nodeToDelete.key);\n this._size--;\n\n if (originalColor === 'BLACK') {\n this._deleteFixup(replacementNode);\n }\n\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n\n return results;\n }\n\n /**\n * Transform entries into a like-kind red-black tree with possibly different key/value types.\n * @remarks Time O(n), Space O(n)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Mapping function from (key, value, index, tree) to a new [key, value].\n * @param [options] - See parameter type for details.\n * @param [thisArg] - See parameter type for details.\n * @returns A new RedBlackTree with mapped entries.\n */\n\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<RedBlackTreeOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): RedBlackTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<RedBlackTreeOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: RedBlackTreeOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<\n TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n > = [],\n options?: Partial<RedBlackTreeOptions<TK, TV, TR>>\n ): RedBlackTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: RedBlackTreeOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n protected override _setRoot(v: RedBlackTreeNode<K, V> | undefined) {\n if (v) {\n v.parent = undefined;\n }\n this._root = v;\n }\n\n protected override _replaceNode(\n oldNode: RedBlackTreeNode<K, V>,\n newNode: RedBlackTreeNode<K, V>\n ): RedBlackTreeNode<K, V> {\n newNode.color = oldNode.color;\n\n return super._replaceNode(oldNode, newNode);\n }\n\n /**\n * (Protected) Standard BST insert followed by red-black fix-up.\n * @remarks Time O(log n), Space O(1)\n * @param node - Node to insert.\n * @returns Status string: 'CREATED' or 'UPDATED'.\n */\n\n protected _insert(node: RedBlackTreeNode<K, V>): CRUD {\n let current = this.root ?? this.NIL;\n let parent: RedBlackTreeNode<K, V> | undefined = undefined;\n\n while (current !== this.NIL) {\n parent = current;\n const compared = this._compare(node.key, current.key);\n if (compared < 0) {\n current = current.left ?? this.NIL;\n } else if (compared > 0) {\n current = current.right ?? this.NIL;\n } else {\n this._replaceNode(current, node);\n return 'UPDATED';\n }\n }\n\n node.parent = parent;\n\n if (!parent) {\n this._setRoot(node);\n } else if (this._compare(node.key, parent.key) < 0) {\n parent.left = node;\n } else {\n parent.right = node;\n }\n\n node.left = this.NIL;\n node.right = this.NIL;\n node.color = 'RED';\n\n this._insertFixup(node);\n return 'CREATED';\n }\n\n /**\n * (Protected) Transplant a subtree in place of another during deletion.\n * @remarks Time O(1), Space O(1)\n * @param u - Node to replace.\n * @param v - Replacement subtree root (may be undefined).\n * @returns void\n */\n\n protected _transplant(u: RedBlackTreeNode<K, V>, v: RedBlackTreeNode<K, V> | undefined): void {\n if (!u.parent) {\n this._setRoot(v);\n } else if (u === u.parent.left) {\n u.parent.left = v;\n } else {\n u.parent.right = v;\n }\n\n if (v) {\n v.parent = u.parent;\n }\n }\n\n /**\n * (Protected) Restore red-black properties after insertion (recolor/rotate).\n * @remarks Time O(log n), Space O(1)\n * @param z - Recently inserted node.\n * @returns void\n */\n\n protected _insertFixup(z: RedBlackTreeNode<K, V> | undefined): void {\n while (z?.parent?.color === 'RED') {\n if (z.parent === z.parent.parent?.left) {\n const y = z.parent.parent.right;\n if (y?.color === 'RED') {\n z.parent.color = 'BLACK';\n y.color = 'BLACK';\n z.parent.parent.color = 'RED';\n\n z = z.parent.parent;\n } else {\n if (z === z.parent.right) {\n z = z.parent;\n this._leftRotate(z);\n }\n\n if (z && z.parent && z.parent.parent) {\n z.parent.color = 'BLACK';\n z.parent.parent.color = 'RED';\n this._rightRotate(z.parent.parent);\n }\n }\n } else {\n const y: RedBlackTreeNode<K, V> | undefined = z?.parent?.parent?.left ?? undefined;\n if (y?.color === 'RED') {\n z.parent.color = 'BLACK';\n y.color = 'BLACK';\n z.parent.parent!.color = 'RED';\n z = z.parent.parent;\n } else {\n if (z === z.parent.left) {\n z = z.parent;\n this._rightRotate(z);\n }\n\n if (z && z.parent && z.parent.parent) {\n z.parent.color = 'BLACK';\n z.parent.parent.color = 'RED';\n this._leftRotate(z.parent.parent);\n }\n }\n }\n }\n\n if (this.isRealNode(this._root)) this._root.color = 'BLACK';\n }\n\n /**\n * (Protected) Restore red-black properties after deletion (recolor/rotate).\n * @remarks Time O(log n), Space O(1)\n * @param node - Child that replaced the deleted node (may be undefined).\n * @returns void\n */\n\n protected _deleteFixup(node: RedBlackTreeNode<K, V> | undefined): void {\n if (!node || node === this.root || node.color === 'BLACK') {\n if (node) {\n node.color = 'BLACK';\n }\n return;\n }\n\n while (node && node !== this.root && node.color === 'BLACK') {\n const parent: RedBlackTreeNode<K, V> | undefined = node.parent;\n\n if (!parent) {\n break;\n }\n\n if (node === parent.left) {\n let sibling = parent.right;\n\n if (sibling?.color === 'RED') {\n sibling.color = 'BLACK';\n parent.color = 'RED';\n this._leftRotate(parent);\n sibling = parent.right;\n }\n\n if ((sibling?.left?.color ?? 'BLACK') === 'BLACK') {\n if (sibling) sibling.color = 'RED';\n node = parent;\n } else {\n if (sibling?.left) sibling.left.color = 'BLACK';\n if (sibling) sibling.color = parent.color;\n parent.color = 'BLACK';\n this._rightRotate(parent);\n node = this.root;\n }\n } else {\n let sibling = parent.left;\n\n if (sibling?.color === 'RED') {\n sibling.color = 'BLACK';\n if (parent) parent.color = 'RED';\n this._rightRotate(parent);\n if (parent) sibling = parent.left;\n }\n\n if ((sibling?.right?.color ?? 'BLACK') === 'BLACK') {\n if (sibling) sibling.color = 'RED';\n node = parent;\n } else {\n if (sibling?.right) sibling.right.color = 'BLACK';\n if (sibling) sibling.color = parent.color;\n if (parent) parent.color = 'BLACK';\n this._leftRotate(parent);\n node = this.root;\n }\n }\n }\n\n if (node) {\n node.color = 'BLACK';\n }\n }\n\n /**\n * (Protected) Perform a left rotation around x.\n * @remarks Time O(1), Space O(1)\n * @param x - Pivot node to rotate around.\n * @returns void\n */\n\n protected _leftRotate(x: RedBlackTreeNode<K, V> | undefined): void {\n if (!x || !x.right) {\n return;\n }\n\n const y = x.right;\n x.right = y.left;\n\n if (y.left && y.left !== this.NIL) {\n y.left.parent = x;\n }\n\n y.parent = x.parent;\n\n if (!x.parent) {\n this._setRoot(y);\n } else if (x === x.parent.left) {\n x.parent.left = y;\n } else {\n x.parent.right = y;\n }\n\n y.left = x;\n x.parent = y;\n }\n\n /**\n * (Protected) Perform a right rotation around y.\n * @remarks Time O(1), Space O(1)\n * @param y - Pivot node to rotate around.\n * @returns void\n */\n\n protected _rightRotate(y: RedBlackTreeNode<K, V> | undefined): void {\n if (!y || !y.left) {\n return;\n }\n\n const x = y.left;\n y.left = x.right;\n\n if (x.right && x.right !== this.NIL) {\n x.right.parent = y;\n }\n\n x.parent = y.parent;\n\n if (!y.parent) {\n this._setRoot(x);\n } else if (y === y.parent.left) {\n y.parent.left = x;\n } else {\n y.parent.right = x;\n }\n\n x.right = y;\n y.parent = x;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n AVLTreeMultiMapOptions,\n BTNOptKeyOrNull,\n ElemOf,\n EntryCallback,\n FamilyPosition,\n IterationType,\n RBTNColor\n} from '../../types';\nimport { AVLTree, AVLTreeNode } from './avl-tree';\nimport { IBinaryTree } from '../../interfaces';\n\n/**\n * Node used by AVLTreeMultiMap; stores the key with a bucket of values (array).\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class AVLTreeMultiMapNode<K = any, V = any> {\n key: K;\n value?: V[];\n parent?: AVLTreeMultiMapNode<K, V> = undefined;\n\n /**\n * Create an AVLTreeMultiMap node with a value bucket.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param value - Initial array of values.\n * @returns New AVLTreeMultiMapNode instance.\n */\n constructor(key: K, value: V[] = []) {\n this.key = key;\n this.value = value;\n }\n\n _left?: AVLTreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): AVLTreeMultiMapNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: AVLTreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: AVLTreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): AVLTreeMultiMapNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: AVLTreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * AVL-tree–based multimap (key → array of values). Preserves O(log N) updates and supports map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n */\nexport class AVLTreeMultiMap<K = any, V = any, R = any> extends AVLTree<K, V[], R> implements IBinaryTree<K, V[], R> {\n /**\n * Create an AVLTreeMultiMap and optionally bulk-insert items.\n * @remarks Time O(N log N), Space O(N)\n * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.\n * @param [options] - Options for AVLTreeMultiMap (comparator, reverse, map mode).\n * @returns New AVLTreeMultiMap instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined | R\n > = [],\n options?: AVLTreeMultiMapOptions<K, V[], R>\n ) {\n super([], { ...options, isMapMode: true });\n if (keysNodesEntriesOrRaws) {\n this.addMany(keysNodesEntriesOrRaws);\n }\n }\n\n override createNode(key: K, value: V[] = []): AVLTreeMultiMapNode<K, V> {\n return new AVLTreeMultiMapNode<K, V>(key, this._isMapMode ? [] : value);\n }\n\n /**\n * Checks if the given item is a `AVLTreeMultiMapNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a AVLTreeMultiMapNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): keyNodeOrEntry is AVLTreeMultiMapNode<K, V> {\n return keyNodeOrEntry instanceof AVLTreeMultiMapNode;\n }\n\n override add(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): boolean;\n\n override add(key: K, value: V): boolean;\n\n /**\n * Insert a value or a list of values into the multimap. If the key exists, values are appended.\n * @remarks Time O(log N + M), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry.\n * @param [value] - Single value to add when a bare key is provided.\n * @returns True if inserted or appended; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value?: V\n ): boolean {\n if (this.isRealNode(keyNodeOrEntry)) return super.add(keyNodeOrEntry);\n\n const _commonAdd = (key?: BTNOptKeyOrNull<K>, values?: V[]) => {\n if (key === undefined || key === null) return false;\n\n const _addToValues = () => {\n const existingValues = this.get(key);\n if (existingValues !== undefined && values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n }\n return false;\n };\n\n const _addByNode = () => {\n const existingNode = this.getNode(key);\n if (this.isRealNode(existingNode)) {\n const existingValues = this.get(existingNode);\n if (existingValues === undefined) {\n super.add(key, values);\n return true;\n }\n if (values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n } else {\n return false;\n }\n } else {\n return super.add(key, values);\n }\n };\n\n if (this._isMapMode) {\n return _addByNode() || _addToValues();\n }\n return _addToValues() || _addByNode();\n };\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, values] = keyNodeOrEntry;\n return _commonAdd(key, value !== undefined ? [value] : values);\n }\n\n return _commonAdd(keyNodeOrEntry, value !== undefined ? [value] : undefined);\n }\n\n /**\n * Delete a single value from the bucket at a given key. Removes the key if the bucket becomes empty.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry to locate the bucket.\n * @param value - Value to remove from the bucket.\n * @returns True if the value was removed; false if not found.\n */\n deleteValue(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value: V\n ): boolean {\n const values = this.get(keyNodeOrEntry);\n if (Array.isArray(values)) {\n const index = values.indexOf(value);\n if (index === -1) return false;\n values.splice(index, 1);\n\n if (values.length === 0) this.delete(keyNodeOrEntry);\n\n return true;\n }\n return false;\n }\n\n /**\n * Rebuild the tree into a perfectly balanced form using in-order nodes.\n * @remarks Time O(N), Space O(N)\n * @param [iterationType] - Traversal style to use when constructing the balanced tree.\n * @returns True if rebalancing succeeded (tree not empty).\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n === 0) return false;\n\n this._clearNodes();\n\n const build = (l: number, r: number, parent?: any): any | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m];\n root.left = build(l, m - 1, root);\n root.right = build(m + 1, r, root);\n root.parent = parent;\n const lh = root.left ? root.left.height : -1;\n const rh = root.right ? root.right.height : -1;\n root.height = Math.max(lh, rh) + 1;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n return true;\n }\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MVArr\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new AVLTreeMultiMap when mapping to array values; see overloads.\n */\n override map<MK = K, MVArr extends unknown[] = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MVArr]>,\n options?: Partial<AVLTreeMultiMapOptions<MK, MVArr, MR>>,\n thisArg?: unknown\n ): AVLTreeMultiMap<MK, ElemOf<MVArr>, MR>;\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new AVLTree when mapping to non-array values; see overloads.\n */\n override map<MK = K, MV = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<AVLTreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTree<MK, MV, MR>;\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns The mapped AVLTree or AVLTreeMultiMap depending on MV; see overloads.\n */\n override map<MK, MV, MR extends object>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<AVLTreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let i = 0;\n for (const [k, v] of this) out.add(callback.call(thisArg, v, k, i++, this));\n return out;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(\n options?: Partial<AVLTreeMultiMapOptions<TK, TV, TR>>\n ): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeMultiMapOptions<TK, TV, TR>\n ) => AVLTree<TK, TV, TR>;\n return new Ctor([], { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind AVLTree built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<AVLTreeMultiMapOptions<TK, TV, TR>>\n ): AVLTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeMultiMapOptions<TK, TV, TR>\n ) => AVLTree<TK, TV, TR>;\n return new Ctor(iter, { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) });\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BTNOptKeyOrNull,\n ElemOf,\n EntryCallback,\n FamilyPosition,\n RBTNColor,\n TreeMultiMapOptions\n} from '../../types';\nimport { RedBlackTree, RedBlackTreeNode } from './red-black-tree';\nimport { IBinaryTree } from '../../interfaces';\n\n/**\n * Node used by TreeMultiMap; stores the key with a bucket of values (array).\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class TreeMultiMapNode<K = any, V = any> {\n key: K;\n value?: V[];\n parent?: TreeMultiMapNode<K, V> = undefined;\n\n /**\n * Create a TreeMultiMap node with an optional value bucket.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param [value] - Initial array of values.\n * @returns New TreeMultiMapNode instance.\n */\n constructor(key: K, value: V[] = [], color: RBTNColor = 'BLACK') {\n this.key = key;\n this.value = value;\n this.color = color;\n }\n\n _left?: TreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): TreeMultiMapNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: TreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: TreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): TreeMultiMapNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: TreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Red-Black Tree–based multimap (key → array of values). Preserves O(log N) updates and supports map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n *\n * @example\n * // players ranked by score with their equipment\n * type Equipment = {\n * name: string; // Equipment name\n * quality: 'legendary' | 'epic' | 'rare' | 'common';\n * level: number;\n * };\n *\n * type Player = {\n * name: string;\n * score: number;\n * equipments: Equipment[];\n * };\n *\n * // Mock player data with their scores and equipment\n * const players: Player[] = [\n * {\n * name: 'DragonSlayer',\n * score: 8750,\n * equipments: [\n * { name: 'AWM', quality: 'legendary', level: 85 },\n * { name: 'Level 3 Helmet', quality: 'epic', level: 80 },\n * { name: 'Extended Quickdraw Mag', quality: 'rare', level: 75 },\n * { name: 'Compensator', quality: 'epic', level: 78 },\n * { name: 'Vertical Grip', quality: 'rare', level: 72 }\n * ]\n * },\n * {\n * name: 'ShadowNinja',\n * score: 7200,\n * equipments: [\n * { name: 'M416', quality: 'epic', level: 75 },\n * { name: 'Ghillie Suit', quality: 'rare', level: 70 },\n * { name: 'Red Dot Sight', quality: 'common', level: 65 },\n * { name: 'Extended QuickDraw Mag', quality: 'rare', level: 68 }\n * ]\n * },\n * {\n * name: 'RuneMaster',\n * score: 9100,\n * equipments: [\n * { name: 'KAR98K', quality: 'legendary', level: 90 },\n * { name: 'Level 3 Vest', quality: 'legendary', level: 85 },\n * { name: 'Holographic Sight', quality: 'epic', level: 82 },\n * { name: 'Suppressor', quality: 'legendary', level: 88 },\n * { name: 'Level 3 Backpack', quality: 'epic', level: 80 }\n * ]\n * },\n * {\n * name: 'BattleKing',\n * score: 8500,\n * equipments: [\n * { name: 'AUG', quality: 'epic', level: 82 },\n * { name: 'Red Dot Sight', quality: 'rare', level: 75 },\n * { name: 'Extended Mag', quality: 'common', level: 70 },\n * { name: 'Tactical Stock', quality: 'rare', level: 76 }\n * ]\n * },\n * {\n * name: 'SniperElite',\n * score: 7800,\n * equipments: [\n * { name: 'M24', quality: 'legendary', level: 88 },\n * { name: 'Compensator', quality: 'epic', level: 80 },\n * { name: 'Scope 8x', quality: 'legendary', level: 85 },\n * { name: 'Level 2 Helmet', quality: 'rare', level: 75 }\n * ]\n * },\n * {\n * name: 'RushMaster',\n * score: 7500,\n * equipments: [\n * { name: 'Vector', quality: 'rare', level: 72 },\n * { name: 'Level 2 Helmet', quality: 'common', level: 65 },\n * { name: 'Quickdraw Mag', quality: 'common', level: 60 },\n * { name: 'Laser Sight', quality: 'rare', level: 68 }\n * ]\n * },\n * {\n * name: 'GhostWarrior',\n * score: 8200,\n * equipments: [\n * { name: 'SCAR-L', quality: 'epic', level: 78 },\n * { name: 'Extended Quickdraw Mag', quality: 'rare', level: 70 },\n * { name: 'Holographic Sight', quality: 'epic', level: 75 },\n * { name: 'Suppressor', quality: 'rare', level: 72 },\n * { name: 'Vertical Grip', quality: 'common', level: 65 }\n * ]\n * },\n * {\n * name: 'DeathDealer',\n * score: 7300,\n * equipments: [\n * { name: 'SKS', quality: 'epic', level: 76 },\n * { name: 'Holographic Sight', quality: 'rare', level: 68 },\n * { name: 'Extended Mag', quality: 'common', level: 65 }\n * ]\n * },\n * {\n * name: 'StormRider',\n * score: 8900,\n * equipments: [\n * { name: 'MK14', quality: 'legendary', level: 92 },\n * { name: 'Level 3 Backpack', quality: 'legendary', level: 85 },\n * { name: 'Scope 8x', quality: 'epic', level: 80 },\n * { name: 'Suppressor', quality: 'legendary', level: 88 },\n * { name: 'Tactical Stock', quality: 'rare', level: 75 }\n * ]\n * },\n * {\n * name: 'CombatLegend',\n * score: 7600,\n * equipments: [\n * { name: 'UMP45', quality: 'rare', level: 74 },\n * { name: 'Level 2 Vest', quality: 'common', level: 67 },\n * { name: 'Red Dot Sight', quality: 'common', level: 62 },\n * { name: 'Extended Mag', quality: 'rare', level: 70 }\n * ]\n * }\n * ];\n *\n * // Create a TreeMultiMap for player rankings\n * const playerRankings = new TreeMultiMap<number, Equipment, Player>(players, {\n * toEntryFn: ({ score, equipments }) => [score, equipments],\n * isMapMode: false\n * });\n *\n * const topPlayersEquipments = playerRankings.rangeSearch([8900, 10000], node => playerRankings.get(node));\n * console.log(topPlayersEquipments); // [\n * // [\n * // {\n * // name: 'MK14',\n * // quality: 'legendary',\n * // level: 92\n * // },\n * // { name: 'Level 3 Backpack', quality: 'legendary', level: 85 },\n * // {\n * // name: 'Scope 8x',\n * // quality: 'epic',\n * // level: 80\n * // },\n * // { name: 'Suppressor', quality: 'legendary', level: 88 },\n * // {\n * // name: 'Tactical Stock',\n * // quality: 'rare',\n * // level: 75\n * // }\n * // ],\n * // [\n * // { name: 'KAR98K', quality: 'legendary', level: 90 },\n * // {\n * // name: 'Level 3 Vest',\n * // quality: 'legendary',\n * // level: 85\n * // },\n * // { name: 'Holographic Sight', quality: 'epic', level: 82 },\n * // {\n * // name: 'Suppressor',\n * // quality: 'legendary',\n * // level: 88\n * // },\n * // { name: 'Level 3 Backpack', quality: 'epic', level: 80 }\n * // ]\n * // ];\n */\nexport class TreeMultiMap<K = any, V = any, R = any> extends RedBlackTree<K, V[], R> implements IBinaryTree<K, V[], R> {\n /**\n * Create a TreeMultiMap and optionally bulk-insert items.\n * @remarks Time O(N log N), Space O(N)\n * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.\n * @param [options] - Options for TreeMultiMap (comparator, reverse, map mode).\n * @returns New TreeMultiMap instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined | R\n > = [],\n options?: TreeMultiMapOptions<K, V[], R>\n ) {\n super([], { ...options });\n if (keysNodesEntriesOrRaws) {\n this.addMany(keysNodesEntriesOrRaws);\n }\n }\n\n override createNode(key: K, value: V[] = []): TreeMultiMapNode<K, V> {\n return new TreeMultiMapNode<K, V>(key, this._isMapMode ? [] : value);\n }\n\n /**\n * Checks if the given item is a `TreeMultiMapNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a TreeMultiMapNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): keyNodeOrEntry is TreeMultiMapNode<K, V> {\n return keyNodeOrEntry instanceof TreeMultiMapNode;\n }\n\n override add(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): boolean;\n\n override add(key: K, value: V): boolean;\n\n /**\n * Insert a value or a list of values into the multimap. If the key exists, values are appended.\n * @remarks Time O(log N + M), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry.\n * @param [value] - Single value to add when a bare key is provided.\n * @returns True if inserted or appended; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value?: V\n ): boolean {\n if (this.isRealNode(keyNodeOrEntry)) return super.add(keyNodeOrEntry);\n\n const _commonAdd = (key?: BTNOptKeyOrNull<K>, values?: V[]) => {\n if (key === undefined || key === null) return false;\n\n const _addToValues = () => {\n const existingValues = this.get(key);\n if (existingValues !== undefined && values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n }\n return false;\n };\n\n const _addByNode = () => {\n const existingNode = this.getNode(key);\n if (this.isRealNode(existingNode)) {\n const existingValues = this.get(existingNode);\n if (existingValues === undefined) {\n super.add(key, values);\n return true;\n }\n if (values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n } else {\n return false;\n }\n } else {\n return super.add(key, values);\n }\n };\n\n if (this._isMapMode) {\n return _addByNode() || _addToValues();\n }\n return _addToValues() || _addByNode();\n };\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, values] = keyNodeOrEntry;\n return _commonAdd(key, value !== undefined ? [value] : values);\n }\n\n return _commonAdd(keyNodeOrEntry, value !== undefined ? [value] : undefined);\n }\n\n /**\n * Delete a single value from the bucket at a given key. Removes the key if the bucket becomes empty.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry to locate the bucket.\n * @param value - Value to remove from the bucket.\n * @returns True if the value was removed; false if not found.\n */\n deleteValue(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value: V\n ): boolean {\n const values = this.get(keyNodeOrEntry);\n if (Array.isArray(values)) {\n const index = values.indexOf(value);\n if (index === -1) return false;\n values.splice(index, 1);\n\n if (values.length === 0) this.delete(keyNodeOrEntry);\n\n return true;\n }\n return false;\n }\n\n override map<MK = K, MVArr extends unknown[] = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MVArr]>,\n options?: Partial<TreeMultiMapOptions<MK, MVArr, MR>>,\n thisArg?: unknown\n ): TreeMultiMap<MK, ElemOf<MVArr>, MR>;\n\n override map<MK = K, MV = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<TreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): RedBlackTree<MK, MV, MR>;\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new RedBlackTree (or TreeMultiMap when mapping to array values; see overloads).\n */\n override map<MK, MV, MR extends object>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<TreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): RedBlackTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let i = 0;\n for (const [k, v] of this) out.add(callback.call(thisArg, v, k, i++, this));\n return out;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<TreeMultiMapOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeMultiMapOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor([], { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind RedBlackTree built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<\n TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n > = [],\n options?: Partial<TreeMultiMapOptions<TK, TV, TR>>\n ): RedBlackTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeMultiMapOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor(iter, { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) });\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n BSTNOptKeyOrNode,\n EntryCallback,\n FamilyPosition,\n IterationType,\n OptNode,\n RBTNColor,\n TreeCounterOptions\n} from '../../types';\nimport { BSTNode } from './bst';\nimport { IBinaryTree } from '../../interfaces';\nimport { RedBlackTree } from './red-black-tree';\n\n/**\n * RB-tree node with an extra 'count' field; keeps parent/child links.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class TreeCounterNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: TreeCounterNode<K, V> = undefined;\n\n /**\n * Create a tree counter node.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param [value] - Value associated with the key (ignored in map mode).\n * @param [count] - Initial count for this node (default 1).\n * @param color - Initial color ('RED' or 'BLACK').\n * @returns New TreeCounterNode instance.\n */\n constructor(key: K, value?: V, count = 1, color: RBTNColor = 'BLACK') {\n this.key = key;\n this.value = value;\n this.color = color;\n this.count = count;\n }\n\n _left?: TreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): TreeCounterNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: TreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: TreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): TreeCounterNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: TreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Red-Black Tree–based counter map (key → value with per-node count). Supports O(log N) updates and map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n */\nexport class TreeCounter<K = any, V = any, R = any> extends RedBlackTree<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Create a TreeCounter and optionally bulk-insert items.\n * @remarks Time O(N log N), Space O(N)\n * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.\n * @param [options] - Options for TreeCounter (comparator, reverse, map mode).\n * @returns New TreeCounter instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: TreeCounterOptions<K, V, R>\n ) {\n super([], options);\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected _count = 0;\n\n /**\n * Get the total aggregate count across all nodes.\n * @remarks Time O(1), Space O(1)\n * @returns Total count.\n */\n\n get count(): number {\n return this._count;\n }\n\n /**\n * Compute the total count by traversing the tree (sums node.count).\n * @remarks Time O(N), Space O(H)\n * @returns Total count recomputed from nodes.\n */\n\n getComputedCount(): number {\n let sum = 0;\n this.dfs(node => (sum += node ? node.count : 0));\n return sum;\n }\n\n override createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): TreeCounterNode<K, V> {\n return new TreeCounterNode(key, this._isMapMode ? undefined : value, count, color) as TreeCounterNode<K, V>;\n }\n\n /**\n * Type guard: check whether the input is a TreeCounterNode.\n * @remarks Time O(1), Space O(1)\n * @returns True if the value is a TreeCounterNode.\n */\n\n override isNode(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is TreeCounterNode<K, V> {\n return keyNodeOrEntry instanceof TreeCounterNode;\n }\n\n /**\n * Insert or increment a node and update aggregate count.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.\n * @param [value] - Value when a bare key is provided (ignored in map mode).\n * @param [count] - How much to increase the node's count (default 1).\n * @returns True if inserted/updated; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value, count);\n const orgCount = newNode?.count || 0;\n const isSuccessAdded = super.add(newNode, newValue);\n if (isSuccessAdded) {\n this._count += orgCount;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Delete a node (or decrement its count) and rebalance if needed.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node.\n * @param [ignoreCount] - If true, remove the node regardless of its count.\n * @returns Array of deletion results including deleted node and a rebalance hint when present.\n */\n override delete(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n ignoreCount = false\n ): BinaryTreeDeleteResult<TreeCounterNode<K, V>>[] {\n if (keyNodeOrEntry === null) return [];\n\n const results: BinaryTreeDeleteResult<TreeCounterNode<K, V>>[] = [];\n\n let nodeToDelete: OptNode<TreeCounterNode<K, V>>;\n if (this._isPredicate(keyNodeOrEntry)) nodeToDelete = this.getNode(keyNodeOrEntry);\n else nodeToDelete = this.isRealNode(keyNodeOrEntry) ? keyNodeOrEntry : this.getNode(keyNodeOrEntry);\n if (!nodeToDelete) {\n return results;\n }\n\n let originalColor = nodeToDelete.color;\n let replacementNode: TreeCounterNode<K, V> | undefined;\n\n if (!this.isRealNode(nodeToDelete.left)) {\n if (nodeToDelete.right !== null) replacementNode = nodeToDelete.right;\n if (ignoreCount || nodeToDelete.count <= 1) {\n if (nodeToDelete.right !== null) {\n this._transplant(nodeToDelete, nodeToDelete.right);\n this._count -= nodeToDelete.count;\n }\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n } else if (!this.isRealNode(nodeToDelete.right)) {\n replacementNode = nodeToDelete.left;\n if (ignoreCount || nodeToDelete.count <= 1) {\n this._transplant(nodeToDelete, nodeToDelete.left);\n this._count -= nodeToDelete.count;\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n } else {\n const successor = this.getLeftMost(node => node, nodeToDelete.right);\n if (successor) {\n originalColor = successor.color;\n if (successor.right !== null) replacementNode = successor.right;\n if (successor.parent === nodeToDelete) {\n if (this.isRealNode(replacementNode)) {\n replacementNode.parent = successor;\n }\n } else {\n if (ignoreCount || nodeToDelete.count <= 1) {\n if (successor.right !== null) {\n this._transplant(successor, successor.right);\n this._count -= nodeToDelete.count;\n }\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n successor.right = nodeToDelete.right;\n if (this.isRealNode(successor.right)) {\n successor.right.parent = successor;\n }\n }\n if (ignoreCount || nodeToDelete.count <= 1) {\n this._transplant(nodeToDelete, successor);\n this._count -= nodeToDelete.count;\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n successor.left = nodeToDelete.left;\n if (this.isRealNode(successor.left)) {\n successor.left.parent = successor;\n }\n successor.color = nodeToDelete.color;\n }\n }\n this._size--;\n if (originalColor === 'BLACK') {\n this._deleteFixup(replacementNode);\n }\n\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n\n return results;\n }\n\n /**\n * Remove all nodes and reset aggregate counters.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n override clear() {\n super.clear();\n this._count = 0;\n }\n\n /**\n * Rebuild the tree into a perfectly balanced form using in-order nodes.\n * @remarks Time O(N), Space O(N)\n * @param [iterationType] - Traversal style to use when constructing the balanced tree.\n * @returns True if rebalancing succeeded (tree not empty).\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n < 1) return false;\n\n let total = 0;\n for (const nd of nodes) total += nd ? nd.count : 0;\n\n this._clearNodes();\n\n const build = (l: number, r: number, parent?: TreeCounterNode<K, V>): TreeCounterNode<K, V> | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m]! as TreeCounterNode<K, V>;\n const leftChild = build(l, m - 1, root);\n const rightChild = build(m + 1, r, root);\n root.left = leftChild;\n root.right = rightChild;\n root.parent = parent;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n this._count = total;\n return true;\n }\n\n /**\n * Create a new TreeCounter by mapping each [key, value] entry.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, value, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new TreeCounter with mapped entries.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<TreeCounterOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): TreeCounter<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * Deep copy this tree, preserving map mode and aggregate counts.\n * @remarks Time O(N), Space O(N)\n * @returns A deep copy of this tree.\n */\n override clone(): this {\n const out = this._createInstance<K, V, R>();\n this._clone(out as unknown as any);\n (out as any)._count = (this as any)._count;\n return out as unknown as this;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<TreeCounterOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeCounterOptions<TK, TV, TR>\n ) => this;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind TreeCounter built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<TreeCounterOptions<TK, TV, TR>>\n ): TreeCounter<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeCounterOptions<TK, TV, TR>\n ) => TreeCounter<TK, TV, TR>;\n return new Ctor(iter as unknown as Iterable<TK | any>, {\n ...this._snapshotOptions<TK, TV, TR>(),\n ...(options ?? {})\n });\n }\n\n /**\n * (Protected) Normalize input into a node plus its effective value and count.\n * @remarks Time O(1), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry.\n * @param [value] - Value used when a bare key is provided.\n * @param [count] - Count increment to apply (default 1).\n * @returns Tuple [node, value] where node may be undefined.\n */\n protected override _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): [TreeCounterNode<K, V> | undefined, V | undefined] {\n if (keyNodeOrEntry === undefined || keyNodeOrEntry === null) return [undefined, undefined];\n\n if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, entryValue] = keyNodeOrEntry;\n if (key === undefined || key === null) return [undefined, undefined];\n const finalValue = value ?? entryValue;\n return [this.createNode(key, finalValue, 'BLACK', count), finalValue];\n }\n\n return [this.createNode(keyNodeOrEntry, value, 'BLACK', count), value];\n }\n\n /**\n * (Protected) Swap keys/values/counters between the source and destination nodes.\n * @remarks Time O(1), Space O(1)\n * @param srcNode - Source node (or key) whose properties will be moved.\n * @param destNode - Destination node (or key) to receive properties.\n * @returns Destination node after swap, or undefined.\n */\n protected override _swapProperties(\n srcNode: BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>,\n destNode: BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>\n ): TreeCounterNode<K, V> | undefined {\n srcNode = this.ensureNode(srcNode);\n destNode = this.ensureNode(destNode);\n if (srcNode && destNode) {\n const { key, value, count, color } = destNode;\n const tempNode = this.createNode(key, value, color, count);\n if (tempNode) {\n tempNode.color = color;\n\n destNode.key = srcNode.key;\n if (!this._isMapMode) destNode.value = srcNode.value;\n destNode.count = srcNode.count;\n destNode.color = srcNode.color;\n\n srcNode.key = tempNode.key;\n if (!this._isMapMode) srcNode.value = tempNode.value;\n srcNode.count = tempNode.count;\n srcNode.color = tempNode.color;\n }\n\n return destNode;\n }\n return undefined;\n }\n\n /**\n * (Protected) Replace one node by another and adjust counters accordingly.\n * @remarks Time O(1), Space O(1)\n * @param oldNode - Node being replaced.\n * @param newNode - Replacement node.\n * @returns The new node after replacement.\n */\n\n protected override _replaceNode(\n oldNode: TreeCounterNode<K, V>,\n newNode: TreeCounterNode<K, V>\n ): TreeCounterNode<K, V> {\n newNode.count = oldNode.count + newNode.count;\n return super._replaceNode(oldNode, newNode);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n AVLTreeCounterOptions,\n BinaryTreeDeleteResult,\n BSTNOptKeyOrNode,\n EntryCallback,\n FamilyPosition,\n IterationType,\n RBTNColor\n} from '../../types';\nimport { IBinaryTree } from '../../interfaces';\nimport { AVLTree } from './avl-tree';\n\n/**\n * AVL node with an extra 'count' field; keeps parent/child links.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class AVLTreeCounterNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: AVLTreeCounterNode<K, V> = undefined;\n\n /**\n * Create an AVL counter node.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param [value] - Associated value (ignored in map mode).\n * @param [count] - Initial count for this node (default 1).\n * @returns New AVLTreeCounterNode instance.\n */\n constructor(key: K, value?: V, count = 1) {\n this.key = key;\n this.value = value;\n this.count = count;\n }\n\n _left?: AVLTreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): AVLTreeCounterNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: AVLTreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: AVLTreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): AVLTreeCounterNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: AVLTreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * AVL tree that tracks an aggregate 'count' across nodes; supports balanced insert/delete and map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n */\nexport class AVLTreeCounter<K = any, V = any, R = any> extends AVLTree<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Create a AVLTreeCounter instance\n * @remarks Time O(n), Space O(n)\n * @param keysNodesEntriesOrRaws\n * @param options\n * @returns New AVLTreeCounterNode instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: AVLTreeCounterOptions<K, V, R>\n ) {\n super([], options);\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected _count = 0;\n\n get count(): number {\n return this._count;\n }\n\n /**\n * Compute the total count by traversing the tree (sums node.count).\n * @remarks Time O(N), Space O(H)\n * @returns Total count recomputed from nodes.\n */\n getComputedCount(): number {\n let sum = 0;\n this.dfs(node => (sum += node.count));\n return sum;\n }\n\n override createNode(key: K, value?: V, count?: number): AVLTreeCounterNode<K, V> {\n return new AVLTreeCounterNode(key, this._isMapMode ? undefined : value, count) as AVLTreeCounterNode<K, V>;\n }\n\n /**\n * Type guard: check whether the input is an AVLTreeCounterNode.\n * @remarks Time O(1), Space O(1)\n * @returns True if the value is an AVLTreeCounterNode.\n */\n override isNode(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is AVLTreeCounterNode<K, V> {\n return keyNodeOrEntry instanceof AVLTreeCounterNode;\n }\n\n /**\n * Insert or increment a node and update aggregate count.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.\n * @param [value] - Value when a bare key is provided (ignored in map mode).\n * @param [count] - How much to increase the node's count (default 1).\n * @returns True if inserted/updated; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value, count);\n if (newNode === undefined) return false;\n\n const orgNodeCount = newNode?.count || 0;\n const inserted = super.add(newNode, newValue);\n if (inserted) {\n this._count += orgNodeCount;\n }\n return true;\n }\n\n /**\n * Delete a node (or decrement its count) and rebalance if needed.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node.\n * @param [ignoreCount] - If true, remove the node regardless of its count.\n * @returns Array of deletion results including deleted node and a rebalance hint when present.\n */\n override delete(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n ignoreCount = false\n ): BinaryTreeDeleteResult<AVLTreeCounterNode<K, V>>[] {\n const deletedResult: BinaryTreeDeleteResult<AVLTreeCounterNode<K, V>>[] = [];\n if (!this.root) return deletedResult;\n\n const curr: AVLTreeCounterNode<K, V> | undefined = this.getNode(keyNodeOrEntry) ?? undefined;\n if (!curr) return deletedResult;\n\n const parent: AVLTreeCounterNode<K, V> | undefined = curr?.parent ? curr.parent : undefined;\n let needBalanced: AVLTreeCounterNode<K, V> | undefined = undefined,\n orgCurrent: AVLTreeCounterNode<K, V> | undefined = curr;\n\n if (curr.count > 1 && !ignoreCount) {\n curr.count--;\n this._count--;\n } else {\n if (!curr.left) {\n if (!parent) {\n if (curr.right !== undefined && curr.right !== null) this._setRoot(curr.right);\n } else {\n const { familyPosition: fp } = curr;\n if (fp === 'LEFT' || fp === 'ROOT_LEFT') {\n parent.left = curr.right;\n } else if (fp === 'RIGHT' || fp === 'ROOT_RIGHT') {\n parent.right = curr.right;\n }\n needBalanced = parent;\n }\n } else {\n const leftSubTreeRightMost = curr.left ? this.getRightMost(node => node, curr.left) : undefined;\n if (leftSubTreeRightMost) {\n const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;\n orgCurrent = this._swapProperties(curr, leftSubTreeRightMost);\n if (parentOfLeftSubTreeMax) {\n if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost) {\n parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;\n } else {\n parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;\n }\n needBalanced = parentOfLeftSubTreeMax;\n }\n }\n }\n this._size = this._size - 1;\n\n if (orgCurrent) this._count -= orgCurrent.count;\n }\n\n deletedResult.push({ deleted: orgCurrent, needBalanced });\n\n if (needBalanced) {\n this._balancePath(needBalanced);\n }\n\n return deletedResult;\n }\n\n /**\n * Remove all nodes and reset aggregate counters.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n override clear() {\n super.clear();\n this._count = 0;\n }\n\n /**\n * Rebuild the tree into a perfectly balanced form using in-order nodes.\n * @remarks Time O(N), Space O(N)\n * @param [iterationType] - Traversal style to use when constructing the balanced tree.\n * @returns True if rebalancing succeeded (tree not empty).\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n === 0) return false;\n\n let total = 0;\n for (const nd of nodes) total += nd ? nd.count : 0;\n\n this._clearNodes();\n\n const build = (l: number, r: number, parent?: any): any => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m];\n root.left = build(l, m - 1, root);\n root.right = build(m + 1, r, root);\n root.parent = parent;\n const lh = root.left ? root.left.height : -1;\n const rh = root.right ? root.right.height : -1;\n root.height = Math.max(lh, rh) + 1;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n this._count = total;\n return true;\n }\n\n /**\n * Deep copy this tree, preserving map mode and aggregate counts.\n * @remarks Time O(N), Space O(N)\n * @returns A deep copy of this tree.\n */\n override clone(): this {\n const out = this._createInstance();\n\n if (this._isMapMode) {\n this.bfs(node => out.add(node.key, undefined, node.count));\n } else {\n this.bfs(node => out.add(node.key, node.value, node.count));\n }\n\n if (this._isMapMode) out._store = this._store;\n\n return out as this;\n }\n\n /**\n * Create a new AVLTreeCounter by mapping each [key, value] entry.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, value, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new AVLTreeCounter with mapped entries.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<AVLTreeCounterOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTreeCounter<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(\n options?: Partial<AVLTreeCounterOptions<TK, TV, TR>>\n ): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<\n TK | AVLTreeCounterNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n >,\n opts?: AVLTreeCounterOptions<TK, TV, TR>\n ) => AVLTreeCounter<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind AVLTreeCounter built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<\n TK | AVLTreeCounterNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n > = [],\n options?: Partial<AVLTreeCounterOptions<TK, TV, TR>>\n ): AVLTreeCounter<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<\n TK | AVLTreeCounterNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n >,\n opts?: AVLTreeCounterOptions<TK, TV, TR>\n ) => AVLTreeCounter<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n /**\n * (Protected) Normalize input into a node plus its effective value and count.\n * @remarks Time O(1), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry.\n * @param [value] - Value used when a bare key is provided.\n * @param [count] - Count increment to apply (default 1).\n * @returns Tuple [node, value] where node may be undefined.\n */\n protected override _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): [AVLTreeCounterNode<K, V> | undefined, V | undefined] {\n if (keyNodeOrEntry === undefined || keyNodeOrEntry === null) return [undefined, undefined];\n if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, entryValue] = keyNodeOrEntry;\n if (key === undefined || key === null) return [undefined, undefined];\n const finalValue = value ?? entryValue;\n return [this.createNode(key, finalValue, count), finalValue];\n }\n\n return [this.createNode(keyNodeOrEntry, value, count), value];\n }\n\n /**\n * (Protected) Swap keys/values/counters between the source and destination nodes.\n * @remarks Time O(1), Space O(1)\n * @param srcNode - Source node (or key) whose properties will be moved.\n * @param destNode - Destination node (or key) to receive properties.\n * @returns Destination node after swap, or undefined.\n */\n protected override _swapProperties(\n srcNode: BSTNOptKeyOrNode<K, AVLTreeCounterNode<K, V>>,\n destNode: BSTNOptKeyOrNode<K, AVLTreeCounterNode<K, V>>\n ): AVLTreeCounterNode<K, V> | undefined {\n srcNode = this.ensureNode(srcNode);\n destNode = this.ensureNode(destNode);\n if (srcNode && destNode) {\n const { key, value, count, height } = destNode;\n const tempNode = this.createNode(key, value, count);\n if (tempNode) {\n tempNode.height = height;\n\n destNode.key = srcNode.key;\n if (!this._isMapMode) destNode.value = srcNode.value;\n destNode.count = srcNode.count;\n destNode.height = srcNode.height;\n\n srcNode.key = tempNode.key;\n if (!this._isMapMode) srcNode.value = tempNode.value;\n srcNode.count = tempNode.count;\n srcNode.height = tempNode.height;\n }\n\n return destNode;\n }\n return undefined;\n }\n\n /**\n * (Protected) Replace one node by another and adjust counters accordingly.\n * @remarks Time O(1), Space O(1)\n * @param oldNode - Node being replaced.\n * @param newNode - Replacement node.\n * @returns The new node after replacement.\n */\n protected override _replaceNode(\n oldNode: AVLTreeCounterNode<K, V>,\n newNode: AVLTreeCounterNode<K, V>\n ): AVLTreeCounterNode<K, V> {\n newNode.count = oldNode.count + newNode.count;\n return super._replaceNode(oldNode, newNode);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\n\nimport type { PriorityQueueOptions } from '../../types';\nimport { Heap } from '../heap';\n\n/**\n * @example\n */\nexport class PriorityQueue<E = any, R = any> extends Heap<E, R> {\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Min-oriented priority queue (min-heap) built on {@link PriorityQueue}.\n * The queue removes the smallest element first under the provided comparator.\n * Provide a custom comparator if you store non-primitive objects.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MinPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a min-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Max-oriented priority queue (max-heap) built on {@link PriorityQueue}.\n * The default comparator orders primitive values in descending order. If you store objects,\n * you must provide a custom comparator via {@link PriorityQueueOptions}.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MaxPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a max-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @throws {TypeError} Thrown when using the default comparator with object elements (provide a custom comparator).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { MatrixOptions } from '../../types';\n\n/**\n *\n */\nexport class Matrix {\n /**\n * The constructor function initializes a matrix object with the provided data and options, or with\n * default values if no options are provided.\n * @param {number[][]} data - A 2D array of numbers representing the data for the matrix.\n * @param [options] - The `options` parameter is an optional object that can contain the following\n * properties:\n */\n constructor(data: number[][], options?: MatrixOptions) {\n if (options) {\n const { rows, cols, addFn, subtractFn, multiplyFn } = options;\n if (typeof rows === 'number' && rows > 0) this._rows = rows;\n else this._rows = data.length;\n if (typeof cols === 'number' && cols > 0) this._cols = cols;\n else this._cols = data[0]?.length || 0;\n if (addFn) this._addFn = addFn;\n if (subtractFn) this._subtractFn = subtractFn;\n if (multiplyFn) this._multiplyFn = multiplyFn;\n } else {\n this._rows = data.length;\n this._cols = data[0]?.length ?? 0;\n }\n\n if (data.length > 0) {\n this._data = data;\n } else {\n this._data = [];\n for (let i = 0; i < this.rows; i++) {\n this._data[i] = new Array(this.cols).fill(0);\n }\n }\n }\n\n protected _rows: number = 0;\n\n /**\n * The function returns the number of rows.\n * @returns The number of rows.\n */\n get rows(): number {\n return this._rows;\n }\n\n protected _cols: number = 0;\n\n /**\n * The function returns the value of the protected variable _cols.\n * @returns The number of columns.\n */\n get cols(): number {\n return this._cols;\n }\n\n protected _data: number[][];\n\n /**\n * The function returns a two-dimensional array of numbers.\n * @returns The data property, which is a two-dimensional array of numbers.\n */\n get data(): number[][] {\n return this._data;\n }\n\n /**\n * The above function returns the value of the _addFn property.\n * @returns The value of the property `_addFn` is being returned.\n */\n get addFn() {\n return this._addFn;\n }\n\n /**\n * The function returns the value of the _subtractFn property.\n * @returns The `_subtractFn` property is being returned.\n */\n get subtractFn() {\n return this._subtractFn;\n }\n\n /**\n * The function returns the value of the _multiplyFn property.\n * @returns The `_multiplyFn` property is being returned.\n */\n get multiplyFn() {\n return this._multiplyFn;\n }\n\n /**\n * The `get` function returns the value at the specified row and column index if it is a valid index.\n * @param {number} row - The `row` parameter represents the row index of the element you want to\n * retrieve from the data array.\n * @param {number} col - The parameter \"col\" represents the column number of the element you want to\n * retrieve from the data array.\n * @returns The `get` function returns a number if the provided row and column indices are valid.\n * Otherwise, it returns `undefined`.\n */\n get(row: number, col: number): number | undefined {\n if (this.isValidIndex(row, col)) {\n return this.data[row][col];\n }\n }\n\n /**\n * The set function updates the value at a specified row and column in a two-dimensional array.\n * @param {number} row - The \"row\" parameter represents the row index of the element in a\n * two-dimensional array or matrix. It specifies the row where the value will be set.\n * @param {number} col - The \"col\" parameter represents the column index of the element in a\n * two-dimensional array.\n * @param {number} value - The value parameter represents the number that you want to set at the\n * specified row and column in the data array.\n * @returns a boolean value. It returns true if the index (row, col) is valid and the value is\n * successfully set in the data array. It returns false if the index is invalid and the value is not\n * set.\n */\n set(row: number, col: number, value: number): boolean {\n if (this.isValidIndex(row, col)) {\n this.data[row][col] = value;\n return true;\n }\n return false;\n }\n\n /**\n * The function checks if the dimensions of the given matrix match the dimensions of the current\n * matrix.\n * @param {Matrix} matrix - The parameter `matrix` is of type `Matrix`.\n * @returns a boolean value.\n */\n isMatchForCalculate(matrix: Matrix): boolean {\n return this.rows === matrix.rows && this.cols === matrix.cols;\n }\n\n /**\n * The `add` function adds two matrices together, returning a new matrix with the result.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.\n * @returns The `add` method returns a new `Matrix` object that represents the result of adding the\n * current matrix with the provided `matrix` parameter.\n */\n add(matrix: Matrix): Matrix | undefined {\n if (!this.isMatchForCalculate(matrix)) {\n throw new Error('Matrix dimensions must match for addition.');\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < this.cols; j++) {\n const a = this.get(i, j),\n b = matrix.get(i, j);\n if (a !== undefined && b !== undefined) {\n const added = this._addFn(a, b);\n if (added) {\n resultData[i][j] = added;\n }\n }\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The `subtract` function performs element-wise subtraction between two matrices and returns a new\n * matrix with the result.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class. It\n * represents the matrix that you want to subtract from the current matrix.\n * @returns a new Matrix object with the result of the subtraction operation.\n */\n subtract(matrix: Matrix): Matrix | undefined {\n if (!this.isMatchForCalculate(matrix)) {\n throw new Error('Matrix dimensions must match for subtraction.');\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < this.cols; j++) {\n const a = this.get(i, j),\n b = matrix.get(i, j);\n if (a !== undefined && b !== undefined) {\n const subtracted = this._subtractFn(a, b);\n if (subtracted) {\n resultData[i][j] = subtracted;\n }\n }\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The `multiply` function performs matrix multiplication between two matrices and returns the result\n * as a new matrix.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.\n * @returns a new Matrix object.\n */\n multiply(matrix: Matrix): Matrix | undefined {\n if (this.cols !== matrix.rows) {\n throw new Error('Matrix dimensions must be compatible for multiplication (A.cols = B.rows).');\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < matrix.cols; j++) {\n let sum: number | undefined;\n for (let k = 0; k < this.cols; k++) {\n const a = this.get(i, k),\n b = matrix.get(k, j);\n if (a !== undefined && b !== undefined) {\n const multiplied = this.multiplyFn(a, b);\n if (multiplied !== undefined) {\n sum = this.addFn(sum, multiplied);\n }\n }\n }\n if (sum !== undefined) resultData[i][j] = sum;\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: matrix.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The transpose function takes a matrix and returns a new matrix that is the transpose of the\n * original matrix.\n * @returns The transpose() function returns a new Matrix object with the transposed data.\n */\n transpose(): Matrix {\n if (this.data.some(row => row.length !== this.rows)) {\n throw new Error('Matrix must be rectangular for transposition.');\n }\n\n const resultData: number[][] = [];\n\n for (let j = 0; j < this.cols; j++) {\n resultData[j] = [];\n for (let i = 0; i < this.rows; i++) {\n const trans = this.get(i, j);\n if (trans !== undefined) resultData[j][i] = trans;\n }\n }\n\n return new Matrix(resultData, {\n rows: this.cols,\n cols: this.rows,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The `inverse` function calculates the inverse of a square matrix using Gaussian elimination.\n * @returns a Matrix object, which represents the inverse of the original matrix.\n */\n inverse(): Matrix | undefined {\n // Check if the matrix is square\n if (this.rows !== this.cols) {\n throw new Error('Matrix must be square for inversion.');\n }\n\n // Create an augmented matrix [this | I]\n const augmentedMatrixData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n augmentedMatrixData[i] = this.data[i].slice(); // Copy the original matrix\n for (let j = 0; j < this.cols; j++) {\n augmentedMatrixData[i][this.cols + j] = i === j ? 1 : 0; // Append the identity matrix\n }\n }\n\n const augmentedMatrix = new Matrix(augmentedMatrixData, {\n rows: this.rows,\n cols: this.cols * 2,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n\n // Apply Gaussian elimination to transform the left half into the identity matrix\n for (let i = 0; i < this.rows; i++) {\n // Find pivot\n let pivotRow = i;\n while (pivotRow < this.rows && augmentedMatrix.get(pivotRow, i) === 0) {\n pivotRow++;\n }\n\n if (pivotRow === this.rows) {\n // Matrix is singular, and its inverse does not exist\n throw new Error('Matrix is singular, and its inverse does not exist.');\n }\n\n // Swap rows to make the pivot the current row\n augmentedMatrix._swapRows(i, pivotRow);\n\n // Scale the pivot row to make the pivot element 1\n const pivotElement = augmentedMatrix.get(i, i) ?? 1;\n\n if (pivotElement === 0) {\n // Handle division by zero\n throw new Error('Matrix is singular, and its inverse does not exist (division by zero).');\n }\n\n augmentedMatrix._scaleRow(i, 1 / pivotElement);\n\n // Eliminate other rows to make elements in the current column zero\n for (let j = 0; j < this.rows; j++) {\n if (j !== i) {\n let factor = augmentedMatrix.get(j, i);\n if (factor === undefined) factor = 0;\n\n augmentedMatrix._addScaledRow(j, i, -factor);\n }\n }\n }\n\n // Extract the right half of the augmented matrix as the inverse\n const inverseData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n inverseData[i] = augmentedMatrix.data[i].slice(this.cols);\n }\n\n return new Matrix(inverseData, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The dot function calculates the dot product of two matrices and returns a new matrix.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.\n * @returns a new Matrix object.\n */\n dot(matrix: Matrix): Matrix | undefined {\n if (this.cols !== matrix.rows) {\n throw new Error(\n 'Number of columns in the first matrix must be equal to the number of rows in the second matrix for dot product.'\n );\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < matrix.cols; j++) {\n let sum: number | undefined;\n for (let k = 0; k < this.cols; k++) {\n const a = this.get(i, k),\n b = matrix.get(k, j);\n if (a !== undefined && b !== undefined) {\n const multiplied = this.multiplyFn(a, b);\n if (multiplied !== undefined) {\n sum = this.addFn(sum, multiplied);\n }\n }\n }\n if (sum !== undefined) resultData[i][j] = sum;\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: matrix.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The function checks if a given row and column index is valid within a specified range.\n * @param {number} row - The `row` parameter represents the row index of a two-dimensional array or\n * matrix. It is a number that indicates the specific row in the matrix.\n * @param {number} col - The \"col\" parameter represents the column index in a two-dimensional array\n * or grid. It is used to check if the given column index is valid within the bounds of the grid.\n * @returns A boolean value is being returned.\n */\n isValidIndex(row: number, col: number): boolean {\n return row >= 0 && row < this.rows && col >= 0 && col < this.cols;\n }\n\n /**\n * The `clone` function returns a new instance of the Matrix class with the same data and properties\n * as the original instance.\n * @returns The `clone()` method is returning a new instance of the `Matrix` class with the same data\n * and properties as the current instance.\n */\n clone(): Matrix {\n return new Matrix(this.data, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n protected _addFn(a: number | undefined, b: number): number | undefined {\n if (a === undefined) return b;\n return a + b;\n }\n\n protected _subtractFn(a: number, b: number) {\n return a - b;\n }\n\n protected _multiplyFn(a: number, b: number) {\n return a * b;\n }\n\n /**\n * The function `_swapRows` swaps the positions of two rows in an array.\n * @param {number} row1 - The `row1` parameter is the index of the first row that you want to swap.\n * @param {number} row2 - The `row2` parameter is the index of the second row that you want to swap\n * with the first row.\n */\n protected _swapRows(row1: number, row2: number): void {\n const temp = this.data[row1];\n this.data[row1] = this.data[row2];\n this.data[row2] = temp;\n }\n\n /**\n * The function scales a specific row in a matrix by a given scalar value.\n * @param {number} row - The `row` parameter represents the index of the row in the matrix that you\n * want to scale. It is a number that indicates the position of the row within the matrix.\n * @param {number} scalar - The scalar parameter is a number that is used to multiply each element in\n * a specific row of a matrix.\n */\n protected _scaleRow(row: number, scalar: number): void {\n for (let j = 0; j < this.cols; j++) {\n let multiplied = this.multiplyFn(this.data[row][j], scalar);\n if (multiplied === undefined) multiplied = 0;\n this.data[row][j] = multiplied;\n }\n }\n\n /**\n * The function `_addScaledRow` multiplies a row in a matrix by a scalar value and adds it to another\n * row.\n * @param {number} targetRow - The targetRow parameter represents the index of the row in which the\n * scaled values will be added.\n * @param {number} sourceRow - The sourceRow parameter represents the index of the row from which the\n * values will be scaled and added to the targetRow.\n * @param {number} scalar - The scalar parameter is a number that is used to scale the values in the\n * source row before adding them to the target row.\n */\n protected _addScaledRow(targetRow: number, sourceRow: number, scalar: number): void {\n for (let j = 0; j < this.cols; j++) {\n let multiplied = this.multiplyFn(this.data[sourceRow][j], scalar);\n if (multiplied === undefined) multiplied = 0;\n const scaledValue = multiplied;\n let added = this.addFn(this.data[targetRow][j], scaledValue);\n if (added === undefined) added = 0;\n this.data[targetRow][j] = added;\n }\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Direction, NavigatorParams, Turning } from '../../types';\n\nexport class Character {\n direction: Direction;\n turn: () => Character;\n\n /**\n * The constructor function takes in a direction and turning object and sets the direction and turn properties of the\n * Character class.\n * @param {Direction} direction - The direction parameter is used to specify the current direction of the character. It\n * can be any value that represents a direction, such as \"north\", \"south\", \"east\", or \"west\".\n * @param {Turning} turning - The `turning` parameter is an object that maps each direction to the corresponding\n * turning direction. It is used to determine the new direction when the character turns.\n */\n constructor(direction: Direction, turning: Turning) {\n this.direction = direction;\n this.turn = () => new Character(turning[direction], turning);\n }\n}\n\n/**\n *\n */\nexport class Navigator<T = number> {\n onMove: (cur: [number, number]) => void;\n protected readonly _matrix: T[][];\n protected readonly _cur: [number, number];\n protected _character: Character;\n protected readonly _VISITED: T;\n\n /**\n * The constructor initializes the Navigator object with the given parameters and sets the current position as visited\n * in the matrix.\n * @param - - `matrix`: a 2D array representing the grid or map\n */\n constructor({ matrix, turning, onMove, init: { cur, charDir, VISITED } }: NavigatorParams<T>) {\n this._matrix = matrix;\n this._cur = cur;\n this._character = new Character(charDir, turning);\n this.onMove = onMove;\n if (this.onMove) this.onMove(this._cur);\n this._VISITED = VISITED;\n this._matrix[this._cur[0]][this._cur[1]] = this._VISITED;\n }\n\n /**\n * The \"start\" function moves the character in its current direction until it encounters an obstacle, then it turns the\n * character and repeats the process.\n */\n start() {\n while (this.check(this._character.direction) || this.check(this._character.turn().direction)) {\n const { direction } = this._character;\n if (this.check(direction)) {\n this.move(direction);\n } else if (this.check(this._character.turn().direction)) {\n this._character = this._character.turn();\n }\n }\n }\n\n /**\n * The function checks if there is a valid move in the specified direction in a matrix.\n * @param {Direction} direction - The direction parameter is a string that represents the direction in which to check.\n * It can be one of the following values: 'up', 'right', 'down', or 'left'.\n * @returns a boolean value.\n */\n check(direction: Direction) {\n let forward: T | undefined, row: T[] | undefined;\n const matrix = this._matrix;\n const [i, j] = this._cur;\n switch (direction) {\n case 'up':\n row = matrix[i - 1];\n if (!row) return false;\n forward = row[j];\n break;\n case 'right':\n forward = matrix[i][j + 1];\n break;\n case 'down':\n row = matrix[i + 1];\n if (!row) return false;\n forward = row[j];\n break;\n case 'left':\n forward = matrix[i][j - 1];\n break;\n }\n return forward !== undefined && forward !== this._VISITED;\n }\n\n /**\n * The `move` function updates the current position based on the given direction and updates the matrix accordingly.\n * @param {Direction} direction - The `direction` parameter is a string that represents the direction in which to move.\n * It can have one of the following values: 'up', 'right', 'down', or 'left'.\n */\n move(direction: Direction) {\n switch (direction) {\n case 'up':\n this._cur[0]--;\n break;\n case 'right':\n this._cur[1]++;\n break;\n case 'down':\n this._cur[0]++;\n break;\n case 'left':\n this._cur[1]--;\n break;\n }\n\n const [i, j] = this._cur;\n this._matrix[i][j] = this._VISITED;\n if (this.onMove) this.onMove(this._cur);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, TrieOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Node used by Trie to store one character and its children.\n * @remarks Time O(1), Space O(1)\n */\nexport class TrieNode {\n /**\n * Create a Trie node with a character key.\n * @remarks Time O(1), Space O(1)\n * @returns New TrieNode instance.\n */\n\n constructor(key: string) {\n this._key = key;\n this._isEnd = false;\n this._children = new Map<string, TrieNode>();\n }\n\n protected _key: string;\n\n /**\n * Get the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Character key string.\n */\n\n get key(): string {\n return this._key;\n }\n\n /**\n * Set the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New character key.\n * @returns void\n */\n\n set key(value: string) {\n this._key = value;\n }\n\n protected _children: Map<string, TrieNode>;\n\n /**\n * Get the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Map from character to child node.\n */\n\n get children(): Map<string, TrieNode> {\n return this._children;\n }\n\n /**\n * Replace the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New map of character → node.\n * @returns void\n */\n\n set children(value: Map<string, TrieNode>) {\n this._children = value;\n }\n\n protected _isEnd: boolean;\n\n /**\n * Check whether this node marks the end of a word.\n * @remarks Time O(1), Space O(1)\n * @returns True if this node ends a word.\n */\n\n get isEnd(): boolean {\n return this._isEnd;\n }\n\n /**\n * Mark this node as the end of a word or not.\n * @remarks Time O(1), Space O(1)\n * @param value - Whether this node ends a word.\n * @returns void\n */\n\n set isEnd(value: boolean) {\n this._isEnd = value;\n }\n}\n\n/**\n * Prefix tree (Trie) for fast prefix queries and word storage.\n * @remarks Time O(1), Space O(1)\n * @template R\n * 1. Node Structure: Each node in a Trie represents a string (or a part of a string). The root node typically represents an empty string.\n * 2. Child Node Relationship: Each node's children represent the strings that can be formed by adding one character to the string at the current node. For example, if a node represents the string 'ca', one of its children might represent 'cat'.\n * 3. Fast Retrieval: Trie allows retrieval in O(m) time complexity, where m is the length of the string to be searched.\n * 4. Space Efficiency: Trie can store a large number of strings very space-efficiently, especially when these strings share common prefixes.\n * 5. Autocomplete and Prediction: Trie can be used for implementing autocomplete and word prediction features, as it can quickly find all strings with a common prefix.\n * 6. Sorting: Trie can be used to sort a set of strings in alphabetical order.\n * 7. String Retrieval: For example, searching for a specific string in a large set of strings.\n * 8. Autocomplete: Providing recommended words or phrases as a user types.\n * 9. Spell Check: Checking the spelling of words.\n * 10. IP Routing: Used in certain types of IP routing algorithms.\n * 11. Text Word Frequency Count: Counting and storing the frequency of words in a large amount of text data.\n * @example\n * // basic Trie creation and add words\n * // Create a simple Trie with initial words\n * const trie = new Trie(['apple', 'app', 'apply']);\n *\n * // Verify size\n * console.log(trie.size); // 3;\n *\n * // Check if words exist\n * console.log(trie.has('apple')); // true;\n * console.log(trie.has('app')); // true;\n *\n * // Add a new word\n * trie.add('application');\n * console.log(trie.size); // 4;\n * @example\n * // Trie getWords and prefix search\n * const trie = new Trie(['apple', 'app', 'apply', 'application', 'apricot']);\n *\n * // Get all words with prefix 'app'\n * const appWords = trie.getWords('app');\n * console.log(appWords); // contains 'app';\n * console.log(appWords); // contains 'apple';\n * console.log(appWords); // contains 'apply';\n * console.log(appWords); // contains 'application';\n * expect(appWords).not.toContain('apricot');\n * @example\n * // Trie isPrefix and isAbsolutePrefix checks\n * const trie = new Trie(['tree', 'trial', 'trick', 'trip', 'trie']);\n *\n * // Check if string is a prefix of any word\n * console.log(trie.hasPrefix('tri')); // true;\n * console.log(trie.hasPrefix('tr')); // true;\n * console.log(trie.hasPrefix('xyz')); // false;\n *\n * // Check if string is an absolute prefix (not a complete word)\n * console.log(trie.hasPurePrefix('tri')); // true;\n * console.log(trie.hasPurePrefix('tree')); // false; // 'tree' is a complete word\n *\n * // Verify size\n * console.log(trie.size); // 5;\n * @example\n * // Trie delete and iteration\n * const trie = new Trie(['car', 'card', 'care', 'careful', 'can', 'cat']);\n *\n * // Delete a word\n * trie.delete('card');\n * console.log(trie.has('card')); // false;\n *\n * // Word with same prefix still exists\n * console.log(trie.has('care')); // true;\n *\n * // Size decreased\n * console.log(trie.size); // 5;\n *\n * // Iterate through all words\n * const allWords = [...trie];\n * console.log(allWords.length); // 5;\n * @example\n * // Trie for autocomplete search index\n * // Trie is perfect for autocomplete: O(m + k) where m is prefix length, k is results\n * const searchIndex = new Trie(['typescript', 'javascript', 'python', 'java', 'rust', 'ruby', 'golang', 'kotlin']);\n *\n * // User types 'j' - get all suggestions\n * const jResults = searchIndex.getWords('j');\n * console.log(jResults); // contains 'javascript';\n * console.log(jResults); // contains 'java';\n * console.log(jResults.length); // 2;\n *\n * // User types 'ja' - get more specific suggestions\n * const jaResults = searchIndex.getWords('ja');\n * console.log(jaResults); // contains 'javascript';\n * console.log(jaResults); // contains 'java';\n * console.log(jaResults.length); // 2;\n *\n * // User types 'jav' - even more specific\n * const javResults = searchIndex.getWords('jav');\n * console.log(javResults); // contains 'javascript';\n * console.log(javResults); // contains 'java';\n * console.log(javResults.length); // 2;\n *\n * // Check for common prefix\n *\n * console.log(searchIndex.hasCommonPrefix('ja')); // false; // Not all words start with 'ja'\n *\n * // Total words in index\n * console.log(searchIndex.size); // 8;\n *\n * // Get height (depth of tree)\n * const height = searchIndex.getHeight();\n * console.log(typeof height); // 'number';\n * @example\n * // Dictionary: Case-insensitive word lookup\n * // Create a case-insensitive dictionary\n * const dictionary = new Trie<string>([], { caseSensitive: false });\n *\n * // Add words with mixed casing\n * dictionary.add('Hello');\n * dictionary.add('WORLD');\n * dictionary.add('JavaScript');\n *\n * // Test lookups with different casings\n * console.log(dictionary.has('hello')); // true;\n * console.log(dictionary.has('HELLO')); // true;\n * console.log(dictionary.has('Hello')); // true;\n * console.log(dictionary.has('javascript')); // true;\n * console.log(dictionary.has('JAVASCRIPT')); // true;\n * @example\n * // File System Path Operations\n * const fileSystem = new Trie<string>([\n * '/home/user/documents/file1.txt',\n * '/home/user/documents/file2.txt',\n * '/home/user/pictures/photo.jpg',\n * '/home/user/pictures/vacation/',\n * '/home/user/downloads'\n * ]);\n *\n * // Find common directory prefix\n * console.log(fileSystem.getLongestCommonPrefix()); // '/home/user/';\n *\n * // List all files in a directory\n * const documentsFiles = fileSystem.getWords('/home/user/documents/');\n * console.log(documentsFiles); // ['/home/user/documents/file1.txt', '/home/user/documents/file2.txt'];\n * @example\n * // IP Address Routing Table\n * // Add IP address prefixes and their corresponding routes\n * const routes = {\n * '192.168.1': 'LAN_SUBNET_1',\n * '192.168.2': 'LAN_SUBNET_2',\n * '10.0.0': 'PRIVATE_NETWORK_1',\n * '10.0.1': 'PRIVATE_NETWORK_2'\n * };\n *\n * const ipRoutingTable = new Trie<string>(Object.keys(routes));\n *\n * // Check IP address prefix matching\n * console.log(ipRoutingTable.hasPrefix('192.168.1')); // true;\n * console.log(ipRoutingTable.hasPrefix('192.168.2')); // true;\n *\n * // Validate IP address belongs to subnet\n * const ip = '192.168.1.100';\n * const subnet = ip.split('.').slice(0, 3).join('.');\n * console.log(ipRoutingTable.hasPrefix(subnet)); // true;\n */\nexport class Trie<R = any> extends IterableElementBase<string, R> {\n /**\n * Create a Trie and optionally bulk-insert words.\n * @remarks Time O(totalChars), Space O(totalChars)\n * @param [words] - Iterable of strings (or raw records if toElementFn is provided).\n * @param [options] - Options such as toElementFn and caseSensitive.\n * @returns New Trie instance.\n */\n\n constructor(words: Iterable<string> | Iterable<R> = [], options?: TrieOptions<R>) {\n super(options);\n if (options) {\n const { caseSensitive } = options;\n if (caseSensitive !== undefined) this._caseSensitive = caseSensitive;\n }\n if (words) {\n this.addMany(words);\n }\n }\n\n protected _size: number = 0;\n\n /**\n * Get the number of stored words.\n * @remarks Time O(1), Space O(1)\n * @returns Word count.\n */\n\n get size(): number {\n return this._size;\n }\n\n protected _caseSensitive: boolean = true;\n\n /**\n * Get whether comparisons are case-sensitive.\n * @remarks Time O(1), Space O(1)\n * @returns True if case-sensitive.\n */\n\n get caseSensitive(): boolean {\n return this._caseSensitive;\n }\n\n protected _root: TrieNode = new TrieNode('');\n\n /**\n * Get the root node.\n * @remarks Time O(1), Space O(1)\n * @returns Root TrieNode.\n */\n\n get root() {\n return this._root;\n }\n\n /**\n * (Protected) Get total count for base class iteration.\n * @remarks Time O(1), Space O(1)\n * @returns Total number of elements.\n */\n\n protected get _total() {\n return this._size;\n }\n\n /**\n * Insert one word into the trie.\n * @remarks Time O(L), Space O(L)\n * @param word - Word to insert.\n * @returns True if the word was newly added.\n */\n\n add(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n let isNewWord = false;\n for (const c of word) {\n let nodeC = cur.children.get(c);\n if (!nodeC) {\n nodeC = new TrieNode(c);\n cur.children.set(c, nodeC);\n }\n cur = nodeC;\n }\n if (!cur.isEnd) {\n isNewWord = true;\n cur.isEnd = true;\n this._size++;\n }\n return isNewWord;\n }\n\n /**\n * Insert many words from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param words - Iterable of strings (or raw records if toElementFn is provided).\n * @returns Array of per-word 'added' flags.\n */\n\n addMany(words: Iterable<string> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const word of words) {\n if (this.toElementFn) {\n ans.push(this.add(this.toElementFn(word as R)));\n } else {\n ans.push(this.add(word as string));\n }\n }\n return ans;\n }\n\n /**\n * Check whether a word exists.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to search for.\n * @returns True if present.\n */\n\n override has(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n for (const c of word) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return cur.isEnd;\n }\n\n /**\n * Check whether the trie is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Remove all words and reset to a fresh root.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._size = 0;\n this._root = new TrieNode('');\n }\n\n /**\n * Delete one word if present.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to delete.\n * @returns True if a word was removed.\n */\n\n delete(word: string): boolean {\n word = this._caseProcess(word);\n let isDeleted = false;\n const dfs = (cur: TrieNode, i: number): boolean => {\n const char = word[i];\n const child = cur.children.get(char);\n if (child) {\n if (i === word.length - 1) {\n if (child.isEnd) {\n if (child.children.size > 0) {\n child.isEnd = false;\n } else {\n cur.children.delete(char);\n }\n isDeleted = true;\n return true;\n }\n return false;\n }\n const res = dfs(child, i + 1);\n if (res && !cur.isEnd && child.children.size === 0) {\n cur.children.delete(char);\n return true;\n }\n return false;\n }\n return false;\n };\n\n dfs(this.root, 0);\n if (isDeleted) {\n this._size--;\n }\n return isDeleted;\n }\n\n /**\n * Compute the height (max depth) of the trie.\n * @remarks Time O(N), Space O(H)\n * @returns Maximum depth from root to a leaf.\n */\n\n getHeight(): number {\n const startNode = this.root;\n let maxDepth = 0;\n if (startNode) {\n const bfs = (node: TrieNode, level: number) => {\n if (level > maxDepth) {\n maxDepth = level;\n }\n const { children } = node;\n if (children) {\n for (const child of children.entries()) {\n bfs(child[1], level + 1);\n }\n }\n };\n bfs(startNode, 0);\n }\n return maxDepth;\n }\n\n /**\n * Check whether input is a proper prefix of at least one word.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input is a prefix but not a full word.\n */\n\n hasPurePrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return !cur.isEnd;\n }\n\n /**\n * Check whether any word starts with input.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input matches a path from root.\n */\n\n hasPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return true;\n }\n\n /**\n * Check whether the trie’s longest common prefix equals input.\n * @remarks Time O(min(H,L)), Space O(1)\n * @param input - Candidate longest common prefix.\n * @returns True if input equals the common prefix.\n */\n\n hasCommonPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (commonPre === input) return;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre === input;\n }\n\n /**\n * Return the longest common prefix among all words.\n * @remarks Time O(H), Space O(1)\n * @returns The longest common prefix string.\n */\n\n getLongestCommonPrefix(): string {\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre;\n }\n\n /**\n * Collect words under a prefix up to a maximum count.\n * @remarks Time O(K·L), Space O(K·L)\n * @param [prefix] - Prefix to match; default empty string for root.\n * @param [max] - Maximum number of words to return; default is Number.MAX_SAFE_INTEGER.\n * @param [isAllWhenEmptyPrefix] - When true, collect from root even if prefix is empty.\n * @returns Array of collected words (at most max).\n */\n\n getWords(prefix = '', max = Number.MAX_SAFE_INTEGER, isAllWhenEmptyPrefix = false): string[] {\n prefix = this._caseProcess(prefix);\n const words: string[] = [];\n let found = 0;\n\n function dfs(node: TrieNode, word: string) {\n for (const char of node.children.keys()) {\n const charNode = node.children.get(char);\n if (charNode !== undefined) {\n dfs(charNode, word.concat(char));\n }\n }\n if (node.isEnd) {\n if (found > max - 1) return;\n words.push(word);\n found++;\n }\n }\n\n let startNode = this.root;\n\n if (prefix) {\n for (const c of prefix) {\n const nodeC = startNode.children.get(c);\n if (nodeC) {\n startNode = nodeC;\n } else {\n return [];\n }\n }\n }\n\n if (isAllWhenEmptyPrefix || startNode !== this.root) dfs(startNode, prefix);\n\n return words;\n }\n\n /**\n * Deep clone this trie by iterating and inserting all words.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @returns A new trie with the same words and options.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this) next.add(x);\n return next;\n }\n\n /**\n * Filter words into a new trie of the same class.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param predicate - Predicate (word, index, trie) → boolean to keep word.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new trie containing words that satisfy the predicate.\n */\n\n filter(predicate: ElementCallback<string, R, boolean>, thisArg?: any): this {\n const results = this._createInstance();\n let index = 0;\n for (const word of this) {\n if (predicate.call(thisArg, word, index, this)) {\n results.add(word);\n }\n index++;\n }\n return results;\n }\n\n map<RM>(callback: ElementCallback<string, R, string>, options?: TrieOptions<RM>, thisArg?: any): Trie<RM>;\n\n /**\n * Map words into a new trie (possibly different record type).\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template EM\n * @template RM\n * @param callback - Mapping function (word, index, trie) → newWord (string).\n * @param [options] - Options for the output trie (e.g., toElementFn, caseSensitive).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Trie constructed from mapped words.\n */\n\n map<EM, RM>(\n callback: ElementCallback<string, R, EM>,\n options?: TrieOptions<RM>,\n thisArg?: any\n ): IterableElementBase<EM, RM>;\n\n map<EM, RM>(callback: ElementCallback<string, R, EM>, options?: TrieOptions<RM>, thisArg?: any): any {\n const newTrie = this._createLike<RM>([], options);\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n if (typeof v !== 'string') {\n throw new TypeError(`Trie.map callback must return string; got ${typeof v}`);\n }\n newTrie.add(v);\n }\n return newTrie;\n }\n\n /**\n * Map words into a new trie of the same element type.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param callback - Mapping function (word, index, trie) → string.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new trie with mapped words.\n */\n\n mapSame(callback: ElementCallback<string, R, string>, thisArg?: any): this {\n const next = this._createInstance();\n let i = 0;\n for (const key of this) {\n const mapped = thisArg === undefined ? callback(key, i++, this) : callback.call(thisArg, key, i++, this);\n next.add(mapped);\n }\n return next;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind trie instance.\n */\n\n protected _createInstance(options?: TrieOptions<R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], {\n toElementFn: this.toElementFn,\n caseSensitive: this.caseSensitive,\n ...(options ?? {})\n });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind trie and seed it from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template RM\n * @param [elements] - Iterable used to seed the new trie.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Trie instance.\n */\n\n protected _createLike<RM>(elements: Iterable<string> | Iterable<RM> = [], options?: TrieOptions<RM>): Trie<RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Trie<RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind trie instance.\n * @remarks Time O(1), Space O(1)\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind Trie instance.\n */\n\n protected _spawnLike<RM>(options?: TrieOptions<RM>): Trie<RM> {\n return this._createLike<RM>([], options);\n }\n\n /**\n * (Protected) Iterate all words in lexicographic order of edges.\n * @remarks Time O(ΣL), Space O(H)\n * @returns Iterator of words.\n */\n\n protected *_getIterator(): IterableIterator<string> {\n function* _dfs(node: TrieNode, path: string): IterableIterator<string> {\n if (node.isEnd) {\n yield path;\n }\n for (const [char, childNode] of node.children) {\n yield* _dfs(childNode, path + char);\n }\n }\n\n yield* _dfs(this.root, '');\n }\n\n /**\n * (Protected) Normalize a string according to case sensitivity.\n * @remarks Time O(L), Space O(L)\n * @param str - Input string to normalize.\n * @returns Normalized string based on caseSensitive.\n */\n\n protected _caseProcess(str: string) {\n if (!this._caseSensitive) {\n str = str.toLowerCase();\n }\n return str;\n }\n}\n","export class TreeNode<V = any> {\n /**\n * The constructor function initializes a TreeNode object with a key, optional value, and optional\n * children.\n * @param {string} key - A string representing the key of the tree node.\n * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the\n * value associated with the node. If no value is provided, it defaults to `undefined`.\n * @param {TreeNode<V>[]} [children] - The `children` parameter is an optional array of `TreeNode<V>`\n * objects. It represents the child nodes of the current node. If no children are provided, the\n * default value is an empty array.\n */\n constructor(key: string, value?: V, children?: TreeNode<V>[]) {\n this._key = key;\n this._value = value || undefined;\n if (children) this._children = children;\n }\n\n protected _key: string;\n\n /**\n * The function returns the value of the protected variable _key.\n * @returns The value of the `_key` property, which is a string.\n */\n get key(): string {\n return this._key;\n }\n\n /**\n * The above function sets the value of a protected variable called \"key\".\n * @param {string} value - The value parameter is a string that represents the value to be assigned\n * to the key.\n */\n set key(value: string) {\n this._key = value;\n }\n\n protected _value?: V | undefined;\n\n /**\n * The function returns the value stored in a variable, or undefined if the variable is empty.\n * @returns The value of the variable `_value` is being returned.\n */\n get value(): V | undefined {\n return this._value;\n }\n\n /**\n * The function sets the value of a variable.\n * @param {V | undefined} value - The parameter \"value\" is of type \"V | undefined\", which means it\n * can accept a value of type \"V\" or it can be undefined.\n */\n set value(value: V | undefined) {\n this._value = value;\n }\n\n protected _children?: TreeNode<V>[] | undefined;\n\n /**\n * The function returns an array of TreeNode objects or undefined.\n * @returns The `children` property is being returned. It is of type `TreeNode<V>[] | undefined`,\n * which means it can either be an array of `TreeNode<V>` objects or `undefined`.\n */\n get children(): TreeNode<V>[] | undefined {\n return this._children;\n }\n\n /**\n * The function sets the value of the children property of a TreeNode object.\n * @param {TreeNode<V>[] | undefined} value - The value parameter is of type TreeNode<V>[] |\n * undefined. This means that it can accept an array of TreeNode objects or undefined.\n */\n set children(value: TreeNode<V>[] | undefined) {\n this._children = value;\n }\n\n /**\n * The function `addChildren` adds one or more child nodes to the current node.\n * @param {TreeNode<V> | TreeNode<V>[]} children - The `children` parameter can be either a single\n * `TreeNode<V>` object or an array of `TreeNode<V>` objects.\n */\n addChildren(children: TreeNode<V> | TreeNode<V>[]) {\n if (!this._children) {\n this._children = [];\n }\n if (children instanceof TreeNode) {\n this._children.push(children);\n } else {\n this._children = this._children.concat(children);\n }\n }\n\n /**\n * The function `getHeight()` calculates the maximum depth of a tree structure by performing a\n * breadth-first search.\n * @returns the maximum depth or height of the tree.\n */\n getHeight() {\n let maxDepth = 0;\n if (this) {\n const bfs = (node: TreeNode<V>, level: number) => {\n if (level > maxDepth) {\n maxDepth = level;\n }\n const { _children } = node;\n if (_children) {\n for (let i = 0, len = _children.length; i < len; i++) {\n bfs(_children[i], level + 1);\n }\n }\n };\n bfs(this, 0);\n }\n return maxDepth;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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A,YAAY;AACV,UAAI,WAAW;AACf,UAAI,MAAM;AACR,cAAM,MAAM,CAAC,MAAmB,UAAkB;AAChD,cAAI,QAAQ,UAAU;AACpB,uBAAW;AAAA,UACb;AACA,gBAAM,EAAE,UAAU,IAAI;AACtB,cAAI,WAAW;AACb,qBAAS,IAAI,GAAG,MAAM,UAAU,QAAQ,IAAI,KAAK,KAAK;AACpD,kBAAI,UAAU,CAAC,GAAG,QAAQ,CAAC;AAAA,YAC7B;AAAA,UACF;AAAA,QACF;AACA,YAAI,MAAM,CAAC;AAAA,MACb;AACA,aAAO;AAAA,IACT;AAAA,EACF;","names":["hash","node","value","visited","DFSOperation","cur","index","sum","value","node","value","value"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-entry-base.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/utils/utils.ts","../../src/utils/number.ts","../../src/data-structures/hash/hash-map.ts","../../src/data-structures/base/linear-base.ts","../../src/data-structures/linked-list/singly-linked-list.ts","../../src/data-structures/linked-list/doubly-linked-list.ts","../../src/data-structures/linked-list/skip-linked-list.ts","../../src/data-structures/stack/stack.ts","../../src/data-structures/queue/queue.ts","../../src/data-structures/queue/deque.ts","../../src/data-structures/heap/heap.ts","../../src/data-structures/heap/max-heap.ts","../../src/data-structures/heap/min-heap.ts","../../src/data-structures/graph/abstract-graph.ts","../../src/data-structures/graph/directed-graph.ts","../../src/data-structures/graph/undirected-graph.ts","../../src/data-structures/graph/map-graph.ts","../../src/common/index.ts","../../src/data-structures/binary-tree/binary-tree.ts","../../src/data-structures/binary-tree/bst.ts","../../src/data-structures/binary-tree/binary-indexed-tree.ts","../../src/data-structures/binary-tree/segment-tree.ts","../../src/data-structures/binary-tree/avl-tree.ts","../../src/data-structures/binary-tree/red-black-tree.ts","../../src/data-structures/binary-tree/avl-tree-multi-map.ts","../../src/data-structures/binary-tree/tree-multi-map.ts","../../src/data-structures/binary-tree/tree-counter.ts","../../src/data-structures/binary-tree/avl-tree-counter.ts","../../src/data-structures/priority-queue/priority-queue.ts","../../src/data-structures/priority-queue/min-priority-queue.ts","../../src/data-structures/priority-queue/max-priority-queue.ts","../../src/data-structures/matrix/matrix.ts","../../src/data-structures/matrix/navigator.ts","../../src/data-structures/trie/trie.ts","../../src/data-structures/tree/tree.ts"],"sourcesContent":["export * from './data-structures';\nexport * from './utils';\nexport * from './interfaces';\nexport * from './types';\nexport * from './common';\n","import type { EntryCallback, ReduceEntryCallback } from '../../types';\n\n/**\n * Iterable view over key-value entries.\n * @template K - Key type.\n * @template V - Value type.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class IterableEntryBase<K = any, V = any> {\n /**\n * Total number of entries.\n * @returns Entry count.\n * @remarks Time O(1), Space O(1)\n */\n abstract get size(): number;\n\n /**\n * Default iterator yielding `[key, value]` entries.\n * @returns Iterator of `[K, V]`.\n * @remarks Time O(n) to iterate, Space O(1)\n */\n *[Symbol.iterator](...args: any[]): IterableIterator<[K, V]> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Iterate over `[key, value]` pairs (may yield `undefined` values).\n * @returns Iterator of `[K, V | undefined]`.\n * @remarks Time O(n), Space O(1)\n */\n *entries(): IterableIterator<[K, V | undefined]> {\n for (const item of this) {\n yield item;\n }\n }\n\n /**\n * Iterate over keys only.\n * @returns Iterator of keys.\n * @remarks Time O(n), Space O(1)\n */\n *keys(): IterableIterator<K> {\n for (const item of this) {\n yield item[0];\n }\n }\n\n /**\n * Iterate over values only.\n * @returns Iterator of values.\n * @remarks Time O(n), Space O(1)\n */\n *values(): IterableIterator<V> {\n for (const item of this) {\n yield item[1];\n }\n }\n\n /**\n * Test whether all entries satisfy the predicate.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns `true` if all pass; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n every(predicate: EntryCallback<K, V, boolean>, thisArg?: any): boolean {\n let index = 0;\n for (const item of this) {\n if (!predicate.call(thisArg, item[1], item[0], index++, this)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Test whether any entry satisfies the predicate.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns `true` if any passes; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n some(predicate: EntryCallback<K, V, boolean>, thisArg?: any): boolean {\n let index = 0;\n for (const item of this) {\n if (predicate.call(thisArg, item[1], item[0], index++, this)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Visit each entry, left-to-right.\n * @param callbackfn - `(key, value, index, self) => void`.\n * @param thisArg - Optional `this` for callback.\n * @remarks Time O(n), Space O(1)\n */\n forEach(callbackfn: EntryCallback<K, V, void>, thisArg?: any): void {\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n callbackfn.call(thisArg, value, key, index++, this);\n }\n }\n\n /**\n * Find the first entry that matches a predicate.\n * @param callbackfn - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns Matching `[key, value]` or `undefined`.\n * @remarks Time O(n), Space O(1)\n */\n find(callbackfn: EntryCallback<K, V, boolean>, thisArg?: any): [K, V] | undefined {\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n if (callbackfn.call(thisArg, value, key, index++, this)) return item;\n }\n return;\n }\n\n /**\n * Whether the given key exists.\n * @param key - Key to test.\n * @returns `true` if found; otherwise `false`.\n * @remarks Time O(n) generic, Space O(1)\n */\n has(key: K): boolean {\n for (const item of this) {\n const [itemKey] = item;\n if (itemKey === key) return true;\n }\n return false;\n }\n\n /**\n * Whether there exists an entry with the given value.\n * @param value - Value to test.\n * @returns `true` if found; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n hasValue(value: V): boolean {\n for (const [, elementValue] of this) {\n if (elementValue === value) return true;\n }\n return false;\n }\n\n /**\n * Get the value under a key.\n * @param key - Key to look up.\n * @returns Value or `undefined`.\n * @remarks Time O(n) generic, Space O(1)\n */\n get(key: K): V | undefined {\n for (const item of this) {\n const [itemKey, value] = item;\n if (itemKey === key) return value;\n }\n return;\n }\n\n /**\n * Reduce entries into a single accumulator.\n * @param callbackfn - `(acc, value, key, index, self) => acc`.\n * @param initialValue - Initial accumulator.\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n reduce<U>(callbackfn: ReduceEntryCallback<K, V, U>, initialValue: U): U {\n let accumulator = initialValue;\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n accumulator = callbackfn(accumulator, value, key, index++, this);\n }\n return accumulator;\n }\n\n /**\n * Converts data structure to `[key, value]` pairs.\n * @returns Array of entries.\n * @remarks Time O(n), Space O(n)\n */\n toArray() {\n return [...this];\n }\n\n /**\n * Visualize the iterable as an array of `[key, value]` pairs (or a custom string).\n * @returns Array of entries (default) or a string.\n * @remarks Time O(n), Space O(n)\n */\n toVisual(): [K, V][] | string {\n return [...this];\n }\n\n /**\n * Print a human-friendly representation to the console.\n * @remarks Time O(n), Space O(n)\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Whether there are no entries.\n * @returns `true` if empty; `false` otherwise.\n * @remarks Time O(1) typical, Space O(1)\n */\n abstract isEmpty(): boolean;\n\n /**\n * Remove all entries.\n * @remarks Time O(n) typical, Space O(1)\n */\n abstract clear(): void;\n\n /**\n * Deep clone preserving the concrete subtype.\n * @returns A new instance of the same concrete class (`this` type).\n * @remarks Time O(n) typical, Space O(n)\n */\n abstract clone(): this;\n\n /**\n * Map entries using an implementation-specific strategy.\n * @remarks Time O(n), Space O(n)\n */\n abstract map(...args: any[]): any;\n\n /**\n * Filter entries and return the same-species structure.\n * @returns A new instance of the same concrete class (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n abstract filter(...args: any[]): this;\n\n /**\n * Underlying iterator for the default iteration protocol.\n * @returns Iterator of `[K, V]`.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getIterator(...args: any[]): IterableIterator<[K, V]>;\n}\n","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Comparable, ComparablePrimitive, Trampoline, TrampolineThunk } from '../types';\n\n/**\n * The function generates a random UUID (Universally Unique Identifier) in TypeScript.\n * @returns A randomly generated UUID (Universally Unique Identifier) in the format\n * 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' where each 'x' is replaced with a random hexadecimal\n * character.\n */\nexport const uuidV4 = function () {\n return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {\n const r = (Math.random() * 16) | 0,\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\n/**\n * The `arrayRemove` function removes elements from an array based on a specified predicate function\n * and returns the removed elements.\n * @param {T[]} array - An array of elements that you want to filter based on the provided predicate\n * function.\n * @param predicate - The `predicate` parameter is a function that takes three arguments:\n * @returns The `arrayRemove` function returns an array containing the elements that satisfy the given\n * `predicate` function.\n */\nexport const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {\n let i = -1,\n len = array ? array.length : 0;\n const result = [];\n\n while (++i < len) {\n const value = array[i];\n if (predicate(value, i, array)) {\n result.push(value);\n Array.prototype.splice.call(array, i--, 1);\n len--;\n }\n }\n\n return result;\n};\n\n/**\n * The function `getMSB` returns the most significant bit of a given number.\n * @param {number} value - The `value` parameter is a number for which we want to find the position of\n * the Most Significant Bit (MSB). The function `getMSB` takes this number as input and calculates the\n * position of the MSB in its binary representation.\n * @returns The function `getMSB` returns the most significant bit (MSB) of the input `value`. If the\n * input value is less than or equal to 0, it returns 0. Otherwise, it calculates the position of the\n * MSB using the `Math.clz32` function and bitwise left shifts 1 to that position.\n */\nexport const getMSB = (value: number): number => {\n if (value <= 0) {\n return 0;\n }\n return 1 << (31 - Math.clz32(value));\n};\n\n/**\n * The `rangeCheck` function in TypeScript is used to validate if an index is within a specified range\n * and throws a `RangeError` with a custom message if it is out of bounds.\n * @param {number} index - The `index` parameter represents the value that you want to check if it\n * falls within a specified range.\n * @param {number} min - The `min` parameter represents the minimum value that the `index` should be\n * compared against in the `rangeCheck` function.\n * @param {number} max - The `max` parameter in the `rangeCheck` function represents the maximum value\n * that the `index` parameter is allowed to have. If the `index` is greater than this `max` value, a\n * `RangeError` will be thrown.\n * @param [message=Index out of bounds.] - The `message` parameter is a string that represents the\n * error message to be thrown if the index is out of bounds. By default, if no message is provided when\n * calling the `rangeCheck` function, the message \"Index out of bounds.\" will be used.\n */\nexport const rangeCheck = (index: number, min: number, max: number, message = 'Index out of bounds.'): void => {\n if (index < min || index > max) throw new RangeError(message);\n};\n\n/**\n * The function `throwRangeError` throws a RangeError with a custom message if called.\n * @param [message=The value is off-limits.] - The `message` parameter is a string that represents the\n * error message to be displayed when a `RangeError` is thrown. If no message is provided, the default\n * message is 'The value is off-limits.'.\n */\nexport const throwRangeError = (message = 'The value is off-limits.'): void => {\n throw new RangeError(message);\n};\n\n/**\n * The function `isWeakKey` checks if the input is an object or a function in TypeScript.\n * @param {unknown} input - The `input` parameter in the `isWeakKey` function is of type `unknown`,\n * which means it can be any type. The function checks if the `input` is an object (excluding `null`)\n * or a function, and returns a boolean indicating whether the `input` is a weak\n * @returns The function `isWeakKey` returns a boolean value indicating whether the input is an object\n * or a function.\n */\nexport const isWeakKey = (input: unknown): input is object => {\n const inputType = typeof input;\n return (inputType === 'object' && input !== null) || inputType === 'function';\n};\n\n/**\n * The function `calcMinUnitsRequired` calculates the minimum number of units required to accommodate a\n * given total quantity based on a specified unit size.\n * @param {number} totalQuantity - The `totalQuantity` parameter represents the total quantity of items\n * that need to be processed or handled.\n * @param {number} unitSize - The `unitSize` parameter represents the size of each unit or package. It\n * is used in the `calcMinUnitsRequired` function to calculate the minimum number of units required to\n * accommodate a total quantity of items.\n */\nexport const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) =>\n Math.floor((totalQuantity + unitSize - 1) / unitSize);\n\n/**\n * The `roundFixed` function in TypeScript rounds a number to a specified number of decimal places.\n * @param {number} num - The `num` parameter is a number that you want to round to a certain number of\n * decimal places.\n * @param {number} [digit=10] - The `digit` parameter in the `roundFixed` function specifies the number\n * of decimal places to round the number to. By default, it is set to 10 if not provided explicitly.\n * @returns The function `roundFixed` returns a number that is rounded to the specified number of\n * decimal places (default is 10 decimal places).\n */\nexport const roundFixed = (num: number, digit: number = 10) => {\n const multiplier = Math.pow(10, digit);\n return Math.round(num * multiplier) / multiplier;\n};\n\n/**\n * The function `isPrimitiveComparable` checks if a value is a primitive type that can be compared.\n * @param {unknown} value - The `value` parameter in the `isPrimitiveComparable` function is of type\n * `unknown`, which means it can be any type. The function checks if the `value` is a primitive type\n * that can be compared, such as number, bigint, string, or boolean.\n * @returns The function `isPrimitiveComparable` returns a boolean value indicating whether the input\n * `value` is a primitive value that can be compared using standard comparison operators (<, >, <=,\n * >=).\n */\nfunction isPrimitiveComparable(value: unknown): value is ComparablePrimitive {\n const valueType = typeof value;\n if (valueType === 'number') return true;\n // if (valueType === 'number') return !Number.isNaN(value);\n return valueType === 'bigint' || valueType === 'string' || valueType === 'boolean';\n}\n\n/**\n * The function `tryObjectToPrimitive` attempts to convert an object to a comparable primitive value by\n * first checking the `valueOf` method and then the `toString` method.\n * @param {object} obj - The `obj` parameter in the `tryObjectToPrimitive` function is an object that\n * you want to convert to a primitive value. The function attempts to convert the object to a primitive\n * value by first checking if the object has a `valueOf` method. If the `valueOf` method exists, it\n * @returns The function `tryObjectToPrimitive` returns a value of type `ComparablePrimitive` if a\n * primitive comparable value is found within the object, or a string value if the object has a custom\n * `toString` method that does not return `'[object Object]'`. If neither condition is met, the\n * function returns `null`.\n */\nfunction tryObjectToPrimitive(obj: object): ComparablePrimitive | null {\n if (typeof obj.valueOf === 'function') {\n const valueOfResult = obj.valueOf();\n if (valueOfResult !== obj) {\n if (isPrimitiveComparable(valueOfResult)) return valueOfResult;\n if (typeof valueOfResult === 'object' && valueOfResult !== null) return tryObjectToPrimitive(valueOfResult);\n }\n }\n if (typeof obj.toString === 'function') {\n const stringResult = obj.toString();\n if (stringResult !== '[object Object]') return stringResult;\n }\n return null;\n}\n\n/**\n * The function `isComparable` in TypeScript checks if a value is comparable, handling primitive values\n * and objects with optional force comparison.\n * @param {unknown} value - The `value` parameter in the `isComparable` function represents the value\n * that you want to check if it is comparable. It can be of any type (`unknown`), and the function will\n * determine if it is comparable based on certain conditions.\n * @param [isForceObjectComparable=false] - The `isForceObjectComparable` parameter in the\n * `isComparable` function is a boolean flag that determines whether to treat non-primitive values as\n * comparable objects. When set to `true`, it forces the function to consider non-primitive values as\n * comparable objects, regardless of their type.\n * @returns The function `isComparable` returns a boolean value indicating whether the `value` is\n * considered comparable or not.\n */\nexport function isComparable(value: unknown, isForceObjectComparable = false): value is Comparable {\n if (value === null || value === undefined) return false;\n if (isPrimitiveComparable(value)) return true;\n\n if (typeof value !== 'object') return false;\n if (value instanceof Date) return true;\n // if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (isForceObjectComparable) return true;\n const comparableValue = tryObjectToPrimitive(value);\n if (comparableValue === null || comparableValue === undefined) return false;\n return isPrimitiveComparable(comparableValue);\n}\n\n/**\n * Creates a trampoline thunk object.\n *\n * A \"thunk\" is a deferred computation — instead of performing a recursive call immediately,\n * it wraps the next step of the computation in a function. This allows recursive processes\n * to be executed iteratively, preventing stack overflows.\n *\n * @template T - The type of the final computation result.\n * @param computation - A function that, when executed, returns the next trampoline step.\n * @returns A TrampolineThunk object containing the deferred computation.\n */\nexport const makeTrampolineThunk = <T>(computation: () => Trampoline<T>): TrampolineThunk<T> => ({\n isThunk: true, // Marker indicating this is a thunk\n fn: computation // The deferred computation function\n});\n\n/**\n * Type guard to check whether a given value is a TrampolineThunk.\n *\n * This function is used to distinguish between a final computation result (value)\n * and a deferred computation (thunk).\n *\n * @template T - The type of the value being checked.\n * @param value - The value to test.\n * @returns True if the value is a valid TrampolineThunk, false otherwise.\n */\nexport const isTrampolineThunk = <T>(value: Trampoline<T>): value is TrampolineThunk<T> =>\n typeof value === 'object' && // Must be an object\n value !== null && // Must not be null\n 'isThunk' in value && // Must have the 'isThunk' property\n value.isThunk; // The flag must be true\n\n/**\n * Executes a trampoline computation until a final (non-thunk) result is obtained.\n *\n * The trampoline function repeatedly invokes the deferred computations (thunks)\n * in an iterative loop. This avoids deep recursive calls and prevents stack overflow,\n * which is particularly useful for implementing recursion in a stack-safe manner.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline value or thunk to start execution from.\n * @returns The final result of the computation (a non-thunk value).\n */\nexport function trampoline<T>(initial: Trampoline<T>): T {\n let current = initial; // Start with the initial trampoline value\n while (isTrampolineThunk(current)) {\n // Keep unwrapping while we have thunks\n current = current.fn(); // Execute the deferred function to get the next step\n }\n return current; // Once no thunks remain, return the final result\n}\n\n/**\n * Wraps a recursive function inside a trampoline executor.\n *\n * This function transforms a potentially recursive function (that returns a Trampoline<Result>)\n * into a *stack-safe* function that executes iteratively using the `trampoline` runner.\n *\n * In other words, it allows you to write functions that look recursive,\n * but actually run in constant stack space.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all trampoline steps are resolved.\n *\n * @param fn - A function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns A new function with the same arguments, but which automatically\n * runs the trampoline process and returns the *final result* instead\n * of a Trampoline.\n *\n * @example\n * // Example: Computing factorial in a stack-safe way\n * const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * console.log(factorial(100000)); // Works without stack overflow\n */\nexport function makeTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> // A function that returns a trampoline step\n): (...args: Args) => Result {\n // Return a wrapped function that automatically runs the trampoline execution loop\n return (...args: Args) => trampoline(fn(...args));\n}\n\n/**\n * Executes an asynchronous trampoline computation until a final (non-thunk) result is obtained.\n *\n * This function repeatedly invokes asynchronous deferred computations (thunks)\n * in an iterative loop. Each thunk may return either a Trampoline<T> or a Promise<Trampoline<T>>.\n *\n * It ensures that asynchronous recursive functions can run without growing the call stack,\n * making it suitable for stack-safe async recursion.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline or Promise of Trampoline to start execution from.\n * @returns A Promise that resolves to the final result (a non-thunk value).\n */\nexport async function asyncTrampoline<T>(initial: Trampoline<T> | Promise<Trampoline<T>>): Promise<T> {\n let current = await initial; // Wait for the initial step to resolve if it's a Promise\n\n // Keep executing thunks until we reach a non-thunk (final) value\n while (isTrampolineThunk(current)) {\n current = await current.fn(); // Execute the thunk function (may be async)\n }\n\n // Once the final value is reached, return it\n return current;\n}\n\n/**\n * Wraps an asynchronous recursive function inside an async trampoline executor.\n *\n * This helper transforms a recursive async function that returns a Trampoline<Result>\n * (or Promise<Trampoline<Result>>) into a *stack-safe* async function that executes\n * iteratively via the `asyncTrampoline` runner.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all async trampoline steps are resolved.\n *\n * @param fn - An async or sync function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns An async function with the same arguments, but which automatically\n * runs the trampoline process and resolves to the *final result*.\n *\n * @example\n * // Example: Async factorial using trampoline\n * const asyncFactorial = makeAsyncTrampoline(async function fact(\n * n: number,\n * acc: number = 1\n * ): Promise<Trampoline<number>> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * asyncFactorial(100000).then(console.log); // Works without stack overflow\n */\nexport function makeAsyncTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>\n): (...args: Args) => Promise<Result> {\n // Return a wrapped async function that runs through the async trampoline loop\n return async (...args: Args): Promise<Result> => {\n return asyncTrampoline(fn(...args));\n };\n}\n","/**\n * The function `toBinaryString` converts a number to a binary string representation with a specified\n * number of digits.\n * @param {number} num - The `num` parameter in the `toBinaryString` function represents the number\n * that you want to convert to a binary string.\n * @param [digit=32] - The `digit` parameter in the `toBinaryString` function represents the number of\n * digits the binary string should have. By default, it is set to 32, meaning that the binary string\n * will be padded with zeros at the beginning to ensure it is 32 bits long. You can provide a\n * @returns The function `toBinaryString` takes a number as input and converts it to a binary string\n * representation with a specified number of digits (default is 32). The binary string is padded with\n * zeros at the beginning to ensure it has the specified number of digits. The function returns the\n * binary string representation of the input number.\n */\nexport function toBinaryString(num: number, digit = 32) {\n // Convert number to binary string\n let binaryString = (num >>> 0).toString(2); // Use the unsigned right shift operator to ensure you get a binary representation of a 32-bit unsigned integer\n\n // Use pad Start to ensure the string length is 32 bits\n binaryString = binaryString.padStart(digit, '0');\n\n return binaryString;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n EntryCallback,\n HashMapLinkedNode,\n HashMapOptions,\n HashMapStoreItem,\n LinkedHashMapOptions\n} from '../../types';\nimport { IterableEntryBase } from '../base';\nimport { isWeakKey, rangeCheck } from '../../utils';\n\n/**\n * Hash-based map. Supports object keys and custom hashing; offers O(1) average set/get/has.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n * 1. Key-Value Pair Storage: HashMap stores key-value pairs. Each key map to a value.\n * 2. Fast Lookup: It's used when you need to quickly find, insert, or delete entries based on a key.\n * 3. Unique Keys: Keys are unique.\n * If you try to insert another entry with the same key, the new one will replace the old entry.\n * 4. Unordered Collection: HashMap does not guarantee the order of entries, and the order may change over time.\n * @example\n * // should maintain insertion order\n * const linkedHashMap = new LinkedHashMap<number, string>();\n * linkedHashMap.set(1, 'A');\n * linkedHashMap.set(2, 'B');\n * linkedHashMap.set(3, 'C');\n *\n * const result = Array.from(linkedHashMap);\n * console.log(result); // [\n * // [1, 'A'],\n * // [2, 'B'],\n * // [3, 'C']\n * // ];\n * @example\n * // basic HashMap creation and set operation\n * // Create a simple HashMap with key-value pairs\n * const map = new HashMap<number, string>([\n * [1, 'one'],\n * [2, 'two'],\n * [3, 'three']\n * ]);\n *\n * // Verify size\n * console.log(map.size); // 3;\n *\n * // Set a new key-value pair\n * map.set(4, 'four');\n * console.log(map.size); // 4;\n *\n * // Verify entries\n * console.log([...map.entries()]); // length: 4;\n * @example\n * // HashMap get and has operations\n * const map = new HashMap<string, number>([\n * ['apple', 1],\n * ['banana', 2],\n * ['cherry', 3]\n * ]);\n *\n * // Check if key exists\n * console.log(map.has('apple')); // true;\n * console.log(map.has('date')); // false;\n *\n * // Get value by key\n * console.log(map.get('banana')); // 2;\n * console.log(map.get('grape')); // undefined;\n *\n * // Get all keys and values\n * const keys = [...map.keys()];\n * const values = [...map.values()];\n * console.log(keys); // contains 'apple';\n * console.log(values); // contains 3;\n * @example\n * // HashMap iteration and filter operations\n * const map = new HashMap<number, string>([\n * [1, 'Alice'],\n * [2, 'Bob'],\n * [3, 'Charlie'],\n * [4, 'Diana'],\n * [5, 'Eve']\n * ]);\n *\n * // Iterate through entries\n * const entries: [number, string][] = [];\n * for (const [key, value] of map) {\n * entries.push([key, value]);\n * }\n * console.log(entries); // length: 5;\n *\n * // Filter operation (for iteration with collection methods)\n * const filtered = [...map].filter(([key]) => key > 2);\n * console.log(filtered.length); // 3;\n *\n * // Map operation\n * const values = [...map.values()].map(v => v.length);\n * console.log(values); // contains 3; // 'Bob', 'Eve'\n * console.log(values); // contains 7;\n * @example\n * // HashMap for user session caching O(1) performance\n * interface UserSession {\n * userId: number;\n * username: string;\n * loginTime: number;\n * lastActivity: number;\n * }\n *\n * // HashMap provides O(1) average-case performance for set/get/delete\n * // Perfect for session management with fast lookups\n * const sessionCache = new HashMap<string, UserSession>();\n *\n * // Simulate user sessions\n * const sessions: [string, UserSession][] = [\n * ['session_001', { userId: 1, username: 'alice', loginTime: 1000, lastActivity: 1050 }],\n * ['session_002', { userId: 2, username: 'bob', loginTime: 1100, lastActivity: 1150 }],\n * ['session_003', { userId: 3, username: 'charlie', loginTime: 1200, lastActivity: 1250 }]\n * ];\n *\n * // Store sessions with O(1) insertion\n * for (const [token, session] of sessions) {\n * sessionCache.set(token, session);\n * }\n *\n * console.log(sessionCache.size); // 3;\n *\n * // Retrieve session with O(1) lookup\n * const userSession = sessionCache.get('session_001');\n * console.log(userSession?.username); // 'alice';\n * console.log(userSession?.userId); // 1;\n *\n * // Update session with O(1) operation\n * if (userSession) {\n * userSession.lastActivity = 2000;\n * sessionCache.set('session_001', userSession);\n * }\n *\n * // Check updated value\n * const updated = sessionCache.get('session_001');\n * console.log(updated?.lastActivity); // 2000;\n *\n * // Cleanup: delete expired sessions\n * sessionCache.delete('session_002');\n * console.log(sessionCache.has('session_002')); // false;\n *\n * // Verify remaining sessions\n * console.log(sessionCache.size); // 2;\n *\n * // Get all active sessions\n * const activeCount = [...sessionCache.values()].length;\n * console.log(activeCount); // 2;\n */\nexport class HashMap<K = any, V = any, R = [K, V]> extends IterableEntryBase<K, V> {\n /**\n * Create a HashMap and optionally bulk-insert entries.\n * @remarks Time O(N), Space O(N)\n * @param [entryOrRawElements] - Iterable of entries or raw elements to insert.\n * @param [options] - Options: hash function and optional record-to-entry converter.\n * @returns New HashMap instance.\n */\n constructor(entryOrRawElements: Iterable<R | [K, V]> = [], options?: HashMapOptions<K, V, R>) {\n super();\n if (options) {\n const { hashFn, toEntryFn } = options;\n if (hashFn) this._hashFn = hashFn;\n if (toEntryFn) this._toEntryFn = toEntryFn;\n }\n if (entryOrRawElements) this.setMany(entryOrRawElements);\n }\n\n protected _store: { [key: string]: HashMapStoreItem<K, V> } = {};\n\n /**\n * Get the internal store for non-object keys.\n * @remarks Time O(1), Space O(1)\n * @returns Internal record of string→{key,value}.\n */\n get store(): { [p: string]: HashMapStoreItem<K, V> } {\n return this._store;\n }\n\n protected _objMap: Map<object, V> = new Map();\n\n /**\n * Get the internal Map used for object/function keys.\n * @remarks Time O(1), Space O(1)\n * @returns Map of object→value.\n */\n get objMap(): Map<object, V> {\n return this._objMap;\n }\n\n protected _toEntryFn?: (rawElement: R) => [K, V];\n\n /**\n * Get the raw→entry converter function if present.\n * @remarks Time O(1), Space O(1)\n * @returns Converter function or undefined.\n */\n get toEntryFn() {\n return this._toEntryFn;\n }\n\n protected _size = 0;\n\n /**\n * Get the number of distinct keys stored.\n * @remarks Time O(1), Space O(1)\n * @returns Current size.\n */\n get size(): number {\n return this._size;\n }\n\n protected _hashFn: (key: K) => string = (key: K) => String(key);\n\n /**\n * Get the current hash function for non-object keys.\n * @remarks Time O(1), Space O(1)\n * @returns Hash function.\n */\n get hashFn() {\n return this._hashFn;\n }\n\n /**\n * Check whether the map is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Remove all entries and reset counters.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n clear(): void {\n this._store = {};\n this._objMap.clear();\n this._size = 0;\n }\n\n /**\n * Type guard: check if a raw value is a [key, value] entry.\n * @remarks Time O(1), Space O(1)\n * @returns True if the value is a 2-tuple.\n */\n isEntry(rawElement: any): rawElement is [K, V] {\n return Array.isArray(rawElement) && rawElement.length === 2;\n }\n\n /**\n * Insert or replace a single entry.\n * @remarks Time O(1), Space O(1)\n * @param key - Key.\n * @param value - Value.\n * @returns True when the operation succeeds.\n */\n set(key: K, value: V): boolean {\n if (this._isObjKey(key)) {\n if (!this.objMap.has(key)) this._size++;\n this.objMap.set(key, value);\n } else {\n const strKey = this._getNoObjKey(key);\n if (this.store[strKey] === undefined) this._size++;\n this._store[strKey] = { key, value };\n }\n return true;\n }\n\n /**\n * Insert many entries from an iterable.\n * @remarks Time O(N), Space O(N)\n * @param entryOrRawElements - Iterable of entries or raw elements to insert.\n * @returns Array of per-entry results.\n */\n setMany(entryOrRawElements: Iterable<R | [K, V]>): boolean[] {\n const results: boolean[] = [];\n for (const rawEle of entryOrRawElements) {\n let key: K | undefined, value: V | undefined;\n if (this.isEntry(rawEle)) [key, value] = rawEle;\n else if (this._toEntryFn) [key, value] = this._toEntryFn(rawEle);\n if (key !== undefined && value !== undefined) results.push(this.set(key, value));\n }\n return results;\n }\n\n /**\n * Get the value for a key.\n * @remarks Time O(1), Space O(1)\n * @param key - Key to look up.\n * @returns Value or undefined.\n */\n override get(key: K): V | undefined {\n if (this._isObjKey(key)) return this.objMap.get(key);\n const strKey = this._getNoObjKey(key);\n return this._store[strKey]?.value;\n }\n\n /**\n * Check if a key exists.\n * @remarks Time O(1), Space O(1)\n * @param key - Key to test.\n * @returns True if present.\n */\n override has(key: K): boolean {\n if (this._isObjKey(key)) return this.objMap.has(key);\n const strKey = this._getNoObjKey(key);\n return strKey in this.store;\n }\n\n /**\n * Delete an entry by key.\n * @remarks Time O(1), Space O(1)\n * @param key - Key to delete.\n * @returns True if the key was found and removed.\n */\n delete(key: K): boolean {\n if (this._isObjKey(key)) {\n if (this.objMap.has(key)) this._size--;\n return this.objMap.delete(key);\n }\n const strKey = this._getNoObjKey(key);\n if (strKey in this.store) {\n delete this.store[strKey];\n this._size--;\n return true;\n }\n return false;\n }\n\n /**\n * Replace the hash function and rehash the non-object store.\n * @remarks Time O(N), Space O(N)\n * @param fn - New hash function for non-object keys.\n * @returns This map instance.\n */\n setHashFn(fn: (key: K) => string): this {\n if (this._hashFn === fn) return this;\n this._hashFn = fn;\n this._rehashNoObj();\n return this;\n }\n\n /**\n * Deep clone this map, preserving hashing behavior.\n * @remarks Time O(N), Space O(N)\n * @returns A new map with the same content.\n */\n clone(): this {\n const opts = { hashFn: this._hashFn, toEntryFn: this._toEntryFn };\n return this._createLike<[K, V], [K, V], [K, V]>(this, opts);\n }\n\n /**\n * Map values to a new map with the same keys.\n * @remarks Time O(N), Space O(N)\n * @template VM\n * @param callbackfn - Mapping function (key, value, index, map) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new map with transformed values.\n */\n map<VM>(callbackfn: EntryCallback<K, V, VM>, thisArg?: any): any {\n const out = this._createLike<K, VM, [K, VM]>();\n let index = 0;\n for (const [key, value] of this) out.set(key, callbackfn.call(thisArg, value, key, index++, this));\n return out;\n }\n\n /**\n * Filter entries into a new map.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (key, value, index, map) → boolean.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new map containing entries that satisfied the predicate.\n */\n\n filter(predicate: EntryCallback<K, V, boolean>, thisArg?: any): any {\n const out = this._createLike<K, V, [K, V]>();\n let index = 0;\n for (const [key, value] of this) if (predicate.call(thisArg, value, key, index++, this)) out.set(key, value);\n return out;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param [entries] - Iterable used to seed the new map.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind map instance.\n */\n protected _createLike<TK = K, TV = V, TR = [TK, TV]>(entries: Iterable<[TK, TV] | TR> = [], options?: any): any {\n const Ctor = this.constructor as new (e?: Iterable<[TK, TV] | TR>, o?: any) => any;\n return new Ctor(entries, options);\n }\n\n protected _rehashNoObj(): void {\n const fresh: Record<string, HashMapStoreItem<K, V>> = {};\n for (const { key, value } of Object.values(this._store)) {\n const sk = this._getNoObjKey(key);\n fresh[sk] = { key, value };\n }\n this._store = fresh;\n }\n\n protected *_getIterator(): IterableIterator<[K, V]> {\n for (const node of Object.values(this.store)) yield [node.key, node.value] as [K, V];\n for (const node of this.objMap) yield node as [K, V];\n }\n\n protected _isObjKey(key: any): key is object | ((...args: any[]) => any) {\n const keyType = typeof key;\n return (keyType === 'object' || keyType === 'function') && key !== null;\n }\n\n protected _getNoObjKey(key: K): string {\n const keyType = typeof key;\n\n let strKey: string;\n if (keyType !== 'string' && keyType !== 'number' && keyType !== 'symbol') {\n strKey = this._hashFn(key);\n } else {\n if (keyType === 'number') {\n strKey = <string>key;\n } else {\n strKey = <string>key;\n }\n }\n return strKey;\n }\n}\n\n/**\n * Hash-based map that preserves insertion order via a doubly-linked list.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n * @example examples will be generated by unit test\n */\nexport class LinkedHashMap<K = any, V = any, R = [K, V]> extends IterableEntryBase<K, V> {\n protected readonly _sentinel: HashMapLinkedNode<K, V | undefined>;\n\n /**\n * Create a LinkedHashMap and optionally bulk-insert entries.\n * @remarks Time O(N), Space O(N)\n * @param [entryOrRawElements] - Iterable of entries or raw elements to insert.\n * @param [options] - Options: hash functions and optional record-to-entry converter.\n * @returns New LinkedHashMap instance.\n */\n constructor(entryOrRawElements: Iterable<R | [K, V]> = [], options?: LinkedHashMapOptions<K, V, R>) {\n super();\n this._sentinel = <HashMapLinkedNode<K, V>>{};\n this._sentinel.prev = this._sentinel.next = this._head = this._tail = this._sentinel;\n\n if (options) {\n const { hashFn, objHashFn, toEntryFn } = options;\n if (hashFn) this._hashFn = hashFn;\n if (objHashFn) this._objHashFn = objHashFn;\n if (toEntryFn) this._toEntryFn = toEntryFn;\n }\n\n if (entryOrRawElements) this.setMany(entryOrRawElements);\n }\n\n protected _hashFn: (key: K) => string = (key: K) => String(key);\n get hashFn(): (key: K) => string {\n return this._hashFn;\n }\n\n protected _objHashFn: (key: K) => object = (key: K) => <object>key;\n\n /**\n * Get the hash function for object/weak keys.\n * @remarks Time O(1), Space O(1)\n * @returns Object-hash function.\n */\n get objHashFn(): (key: K) => object {\n return this._objHashFn;\n }\n\n protected _noObjMap: Record<string, HashMapLinkedNode<K, V | undefined>> = {};\n\n /**\n * Get the internal record for non-object keys.\n * @remarks Time O(1), Space O(1)\n * @returns Record of hash→node.\n */\n get noObjMap(): Record<string, HashMapLinkedNode<K, V | undefined>> {\n return this._noObjMap;\n }\n\n protected _objMap = new WeakMap<object, HashMapLinkedNode<K, V | undefined>>();\n get objMap(): WeakMap<object, HashMapLinkedNode<K, V | undefined>> {\n return this._objMap;\n }\n\n protected _head: HashMapLinkedNode<K, V | undefined>;\n\n /**\n * Get the head node (first entry) sentinel link.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or sentinel.\n */\n get head(): HashMapLinkedNode<K, V | undefined> {\n return this._head;\n }\n\n protected _tail: HashMapLinkedNode<K, V | undefined>;\n\n /**\n * Get the tail node (last entry) sentinel link.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or sentinel.\n */\n get tail(): HashMapLinkedNode<K, V | undefined> {\n return this._tail;\n }\n\n protected _toEntryFn?: (rawElement: R) => [K, V] = (rawElement: R) => {\n if (this.isEntry(rawElement)) {\n return rawElement;\n }\n throw new Error(\n 'If `entryOrRawElements` does not adhere to [key,value], provide `options.toEntryFn` to transform raw records.'\n );\n };\n get toEntryFn() {\n return this._toEntryFn;\n }\n\n protected _size = 0;\n get size() {\n return this._size;\n }\n\n /**\n * Get the first [key, value] pair.\n * @remarks Time O(1), Space O(1)\n * @returns First entry or undefined when empty.\n */\n get first() {\n if (this._size === 0) return;\n return <[K, V]>[this.head.key, this.head.value];\n }\n\n /**\n * Get the last [key, value] pair.\n * @remarks Time O(1), Space O(1)\n * @returns Last entry or undefined when empty.\n */\n get last() {\n if (this._size === 0) return;\n return <[K, V]>[this.tail.key, this.tail.value];\n }\n\n /**\n * Iterate from head → tail.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of [key, value].\n */\n *begin() {\n let node = this.head;\n while (node !== this._sentinel) {\n yield [node.key, node.value];\n node = node.next;\n }\n }\n\n /**\n * Iterate from tail → head.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of [key, value].\n */\n *reverseBegin() {\n let node = this.tail;\n while (node !== this._sentinel) {\n yield [node.key, node.value];\n node = node.prev;\n }\n }\n\n /**\n * Insert or replace a single entry; preserves insertion order.\n * @remarks Time O(1), Space O(1)\n * @param key - Key.\n * @param [value] - Value.\n * @returns True when the operation succeeds.\n */\n set(key: K, value?: V): boolean {\n let node: HashMapLinkedNode<K, V | undefined> | undefined;\n const isNewKey = !this.has(key);\n\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n node = this.objMap.get(hash);\n if (!node && isNewKey) {\n node = { key: <K>hash, value, prev: this.tail, next: this._sentinel };\n this.objMap.set(hash, node);\n } else if (node) {\n node.value = value;\n }\n } else {\n const hash = this._hashFn(key);\n node = this.noObjMap[hash];\n if (!node && isNewKey) {\n this.noObjMap[hash] = node = { key, value, prev: this.tail, next: this._sentinel };\n } else if (node) {\n node.value = value;\n }\n }\n\n if (node && isNewKey) {\n if (this._size === 0) {\n this._head = node;\n this._sentinel.next = node;\n } else {\n this.tail.next = node;\n node.prev = this.tail;\n }\n this._tail = node;\n this._sentinel.prev = node;\n this._size++;\n }\n\n return true;\n }\n\n setMany(entryOrRawElements: Iterable<R | [K, V]>): boolean[] {\n const results: boolean[] = [];\n for (const rawEle of entryOrRawElements) {\n let key: K | undefined, value: V | undefined;\n if (this.isEntry(rawEle)) [key, value] = rawEle;\n else if (this._toEntryFn) [key, value] = this._toEntryFn(rawEle);\n if (key !== undefined && value !== undefined) results.push(this.set(key, value));\n }\n return results;\n }\n\n override has(key: K): boolean {\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n return this.objMap.has(hash);\n }\n const hash = this._hashFn(key);\n return hash in this.noObjMap;\n }\n\n override get(key: K): V | undefined {\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n const node = this.objMap.get(hash);\n return node ? node.value : undefined;\n }\n const hash = this._hashFn(key);\n const node = this.noObjMap[hash];\n return node ? node.value : undefined;\n }\n\n /**\n * Get the value at a given index in insertion order.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Value at the index.\n */\n at(index: number): V | undefined {\n rangeCheck(index, 0, this._size - 1);\n let node = this.head;\n while (index--) node = node.next;\n return node.value;\n }\n\n delete(key: K): boolean {\n let node: HashMapLinkedNode<K, V | undefined> | undefined;\n if (isWeakKey(key)) {\n const hash = this._objHashFn(key);\n node = this.objMap.get(hash);\n if (!node) return false;\n this.objMap.delete(hash);\n } else {\n const hash = this._hashFn(key);\n node = this.noObjMap[hash];\n if (!node) return false;\n delete this.noObjMap[hash];\n }\n return this._deleteNode(node);\n }\n\n /**\n * Delete the first entry that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (key, value, index, map) → boolean to decide deletion.\n * @returns True if an entry was removed.\n */\n deleteWhere(predicate: (key: K, value: V | undefined, index: number, map: this) => boolean): boolean {\n let node = this._head;\n let i = 0;\n while (node !== this._sentinel) {\n const cur = node;\n node = node.next;\n if (predicate(cur.key as K, cur.value as V | undefined, i++, this)) {\n if (isWeakKey(cur.key as unknown as object)) {\n this._objMap.delete(cur.key as unknown as object);\n } else {\n const hash = this._hashFn(cur.key as K);\n delete this._noObjMap[hash];\n }\n return this._deleteNode(cur);\n }\n }\n return false;\n }\n\n /**\n * Delete the entry at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns True if removed.\n */\n deleteAt(index: number): boolean {\n rangeCheck(index, 0, this._size - 1);\n let node = this.head;\n while (index--) node = node.next;\n return this._deleteNode(node);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n isEntry(rawElement: any): rawElement is [K, V] {\n return Array.isArray(rawElement) && rawElement.length === 2;\n }\n\n clear(): void {\n this._noObjMap = {};\n this._size = 0;\n this._head = this._tail = this._sentinel.prev = this._sentinel.next = this._sentinel;\n }\n\n clone(): any {\n const opts = { hashFn: this._hashFn, objHashFn: this._objHashFn };\n return this._createLike<[K, V], [K, V], [K, V]>(this, opts);\n }\n\n filter(predicate: EntryCallback<K, V, boolean>, thisArg?: any): any {\n const out = this._createLike<K, V, [K, V]>();\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, value, key, index, this)) out.set(key, value);\n index++;\n }\n return out;\n }\n\n /**\n * Map each entry to a new [key, value] pair and preserve order.\n * @remarks Time O(N), Space O(N)\n * @template MK\n * @template MV\n * @param callback - Mapping function (key, value, index, map) → [newKey, newValue].\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new map of the same class with transformed entries.\n */\n map<MK, MV>(callback: EntryCallback<K, V, [MK, MV]>, thisArg?: any): any {\n const out = this._createLike<MK, MV, [MK, MV]>();\n let index = 0;\n for (const [key, value] of this) {\n const [newKey, newValue] = callback.call(thisArg, value, key, index, this);\n out.set(newKey, newValue);\n index++;\n }\n return out;\n }\n\n protected *_getIterator(): IterableIterator<[K, V]> {\n let node = this.head;\n while (node !== this._sentinel) {\n yield [node.key, node.value] as [K, V];\n node = node.next;\n }\n }\n\n protected _deleteNode(node: HashMapLinkedNode<K, V | undefined>): boolean {\n const { prev, next } = node;\n prev.next = next;\n next.prev = prev;\n\n if (node === this.head) this._head = next;\n if (node === this.tail) this._tail = prev;\n\n this._size -= 1;\n return true;\n }\n\n protected _createLike<TK = K, TV = V, TR = [TK, TV]>(entries: Iterable<[TK, TV] | TR> = [], options?: any): any {\n const Ctor = this.constructor as new (e?: Iterable<[TK, TV] | TR>, o?: any) => any;\n return new Ctor(entries, options);\n }\n}\n","import type { ElementCallback, LinearBaseOptions, ReduceLinearCallback } from '../../types';\nimport { IterableElementBase } from './iterable-element-base';\n\n/**\n * Singly-linked list node.\n * @template E - Element type.\n * @remarks Time O(1), Space O(1)\n */\nexport class LinkedListNode<E = any> {\n /**\n * Initialize a node.\n * @param value - Element value.\n * @remarks Time O(1), Space O(1)\n */\n constructor(value: E) {\n this._value = value;\n this._next = undefined;\n }\n\n protected _value: E;\n\n /**\n * Element payload getter.\n * @returns Element value.\n * @remarks Time O(1), Space O(1)\n */\n get value(): E {\n return this._value;\n }\n\n /**\n * Element payload setter.\n * @param value - New value.\n * @remarks Time O(1), Space O(1)\n */\n set value(value: E) {\n this._value = value;\n }\n\n protected _next: LinkedListNode<E> | undefined;\n\n /**\n * Next node getter.\n * @returns Next node or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n get next(): LinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Next node setter.\n * @param value - Next node or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n set next(value: LinkedListNode<E> | undefined) {\n this._next = value;\n }\n}\n\n/**\n * Abstract linear container with array-like utilities.\n * @template E - Element type.\n * @template R - Return type for mapped/derived views.\n * @template NODE - Linked node type used by some implementations.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class LinearBase<\n E,\n R = any,\n NODE extends LinkedListNode<E> = LinkedListNode<E>\n> extends IterableElementBase<E, R> {\n /**\n * Construct a linear container with runtime options.\n * @param options - `{ maxLen?, ... }` bounds/behavior options.\n * @remarks Time O(1), Space O(1)\n */\n protected constructor(options?: LinearBaseOptions<E, R>) {\n super(options);\n if (options) {\n const { maxLen } = options;\n if (typeof maxLen === 'number' && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;\n }\n }\n\n /**\n * Element count.\n * @returns Number of elements.\n * @remarks Time O(1), Space O(1)\n */\n abstract get length(): number;\n\n protected _maxLen: number = -1;\n\n /**\n * Upper bound for length (if positive), or `-1` when unbounded.\n * @returns Maximum allowed length.\n * @remarks Time O(1), Space O(1)\n */\n get maxLen() {\n return this._maxLen;\n }\n\n /**\n * First index of a value from the left.\n * @param searchElement - Value to match.\n * @param fromIndex - Start position (supports negative index).\n * @returns Index or `-1` if not found.\n * @remarks Time O(n), Space O(1)\n */\n indexOf(searchElement: E, fromIndex: number = 0): number {\n if (this.length === 0) return -1;\n if (fromIndex < 0) fromIndex = this.length + fromIndex;\n if (fromIndex < 0) fromIndex = 0;\n\n for (let i = fromIndex; i < this.length; i++) {\n const element = this.at(i);\n if (element === searchElement) return i;\n }\n\n return -1;\n }\n\n /**\n * Last index of a value from the right.\n * @param searchElement - Value to match.\n * @param fromIndex - Start position (supports negative index).\n * @returns Index or `-1` if not found.\n * @remarks Time O(n), Space O(1)\n */\n lastIndexOf(searchElement: E, fromIndex: number = this.length - 1): number {\n if (this.length === 0) return -1;\n if (fromIndex >= this.length) fromIndex = this.length - 1;\n if (fromIndex < 0) fromIndex = this.length + fromIndex;\n\n for (let i = fromIndex; i >= 0; i--) {\n const element = this.at(i);\n if (element === searchElement) return i;\n }\n\n return -1;\n }\n\n /**\n * Find the first index matching a predicate.\n * @param predicate - `(element, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n findIndex(predicate: ElementCallback<E, R, boolean>, thisArg?: any): number {\n for (let i = 0; i < this.length; i++) {\n const item = this.at(i);\n if (item !== undefined && predicate.call(thisArg, item, i, this)) return i;\n }\n return -1;\n }\n\n /**\n * Concatenate multiple containers of the same species.\n * @param items - Other lists to append.\n * @returns New container with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n concat(...items: this[]): this;\n\n /**\n * Concatenate elements and/or containers.\n * @param items - Elements or other containers.\n * @returns New container with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n concat(...items: (E | this)[]): this {\n const newList = this.clone();\n\n for (const item of items) {\n if (item instanceof LinearBase) {\n newList.pushMany(item);\n } else {\n newList.push(item);\n }\n }\n\n return newList;\n }\n\n /**\n * In-place stable order via array sort semantics.\n * @param compareFn - Comparator `(a, b) => number`.\n * @returns This container.\n * @remarks Time O(n log n), Space O(n) (materializes to array temporarily)\n */\n sort(compareFn?: (a: E, b: E) => number): this {\n const arr = this.toArray();\n arr.sort(compareFn);\n this.clear();\n for (const item of arr) this.push(item);\n return this;\n }\n\n /**\n * Remove and/or insert elements at a position (array-compatible).\n * @param start - Start index (supports negative index).\n * @param deleteCount - How many to remove.\n * @param items - Elements to insert.\n * @returns Removed elements as a new list (`this` type).\n * @remarks Time O(n + m), Space O(min(n, m)) where `m = items.length`\n */\n splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n const removedList = this._createInstance();\n\n start = start < 0 ? this.length + start : start;\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));\n\n for (let i = 0; i < deleteCount; i++) {\n const removed = this.deleteAt(start);\n if (removed !== undefined) {\n removedList.push(removed);\n }\n }\n\n for (let i = 0; i < items.length; i++) {\n this.addAt(start + i, items[i]);\n }\n\n return removedList;\n }\n\n /**\n * Join all elements into a string.\n * @param separator - Separator string.\n * @returns Concatenated string.\n * @remarks Time O(n), Space O(n)\n */\n join(separator: string = ','): string {\n return this.toArray().join(separator);\n }\n\n /**\n * Snapshot elements into a reversed array.\n * @returns New reversed array.\n * @remarks Time O(n), Space O(n)\n */\n toReversedArray(): E[] {\n const array: E[] = [];\n for (let i = this.length - 1; i >= 0; i--) {\n array.push(this.at(i)!);\n }\n return array;\n }\n\n reduceRight(callbackfn: ReduceLinearCallback<E>): E;\n\n reduceRight(callbackfn: ReduceLinearCallback<E>, initialValue: E): E;\n\n /**\n * Right-to-left reduction over elements.\n * @param callbackfn - `(acc, element, index, self) => acc`.\n * @param initialValue - Initial accumulator (optional generic overloads supported).\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue: U): U;\n\n reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue?: U): U {\n let accumulator = initialValue ?? (0 as U);\n for (let i = this.length - 1; i >= 0; i--) {\n accumulator = callbackfn(accumulator, this.at(i)!, i, this);\n }\n return accumulator;\n }\n\n /**\n * Create a shallow copy of a subrange.\n * @param start - Inclusive start (supports negative index).\n * @param end - Exclusive end (supports negative index).\n * @returns New list with the range (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n slice(start: number = 0, end: number = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n const newList = this._createInstance();\n for (let i = start; i < end; i++) {\n newList.push(this.at(i)!);\n }\n return newList;\n }\n\n /**\n * Fill a range with a value.\n * @param value - Value to set.\n * @param start - Inclusive start.\n * @param end - Exclusive end.\n * @returns This list.\n * @remarks Time O(n), Space O(1)\n */\n fill(value: E, start = 0, end = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n if (start < 0) start = 0;\n if (end > this.length) end = this.length;\n if (start >= end) return this;\n\n for (let i = start; i < end; i++) {\n this.setAt(i, value);\n }\n\n return this;\n }\n\n /**\n * Set the value at an index.\n * @param index - Position (0-based).\n * @param value - New value.\n * @returns `true` if updated.\n * @remarks Time O(1) typical, Space O(1)\n */\n abstract setAt(index: number, value: E): boolean;\n\n /**\n * Deep clone while preserving concrete subtype.\n * @returns New list of the same species (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n abstract override clone(): this;\n\n /**\n * Reverse the order of elements in-place (or equivalent).\n * @returns This list.\n * @remarks Time O(n), Space O(1)\n */\n abstract reverse(): this;\n\n /**\n * Append one element or node to the tail.\n * @param elementOrNode - Element or node.\n * @returns `true` if appended.\n * @remarks Time O(1) amortized typical, Space O(1)\n */\n abstract push(elementOrNode: E | NODE): boolean;\n\n /**\n * Append many elements/nodes at once.\n * @param elements - Iterable of elements or nodes.\n * @returns Array of booleans indicating append success.\n * @remarks Time O(n), Space O(1)\n */\n abstract pushMany(elements: Iterable<E> | Iterable<R> | Iterable<NODE>): boolean[];\n\n /**\n * Remove one element or node if present.\n * @param elementOrNode - Element or node to delete.\n * @returns `true` if removed.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract delete(elementOrNode: E | NODE | undefined): boolean;\n\n /**\n * Get element at an index.\n * @param index - Position (0-based).\n * @returns Element or `undefined`.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract at(index: number): E | undefined;\n\n /**\n * Remove element at a position.\n * @param pos - Position (0-based).\n * @returns Removed element or `undefined`.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract deleteAt(pos: number): E | undefined;\n\n /**\n * Insert an element/node at a position.\n * @param index - Position (0-based).\n * @param newElementOrNode - Element or node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract addAt(index: number, newElementOrNode: E | NODE): boolean;\n\n /**\n * Create an empty list of the same species.\n * @param options - Runtime options to carry.\n * @returns Empty list (`this` type).\n * @remarks Time O(1), Space O(1)\n */\n protected abstract _createInstance(options?: LinearBaseOptions<E, R>): this;\n\n /**\n * Reverse-direction iterator over elements.\n * @returns Iterator of elements from tail to head.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getReverseIterator(...args: any[]): IterableIterator<E>;\n}\n\n/**\n * Linked-list specialized linear container.\n * @template E - Element type.\n * @template R - Return type for mapped/derived views.\n * @template NODE - Linked node type.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class LinearLinkedBase<\n E,\n R = any,\n NODE extends LinkedListNode<E> = LinkedListNode<E>\n> extends LinearBase<E, R, NODE> {\n protected constructor(options?: LinearBaseOptions<E, R>) {\n super(options);\n if (options) {\n const { maxLen } = options;\n if (typeof maxLen === 'number' && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;\n }\n }\n\n /**\n * Linked-list optimized `indexOf` (forwards scan).\n * @param searchElement - Value to match.\n * @param fromIndex - Start position.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n override indexOf(searchElement: E, fromIndex: number = 0): number {\n const iterator = this._getIterator();\n let current = iterator.next();\n\n let index = 0;\n while (index < fromIndex) {\n current = iterator.next();\n index++;\n }\n\n while (!current.done) {\n if (current.value === searchElement) return index;\n current = iterator.next();\n index++;\n }\n\n return -1;\n }\n\n /**\n * Linked-list optimized `lastIndexOf` (reverse scan).\n * @param searchElement - Value to match.\n * @param fromIndex - Start position.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n override lastIndexOf(searchElement: E, fromIndex: number = this.length - 1): number {\n const iterator = this._getReverseIterator();\n let current = iterator.next();\n\n let index = this.length - 1;\n while (index > fromIndex) {\n current = iterator.next();\n index--;\n }\n\n while (!current.done) {\n if (current.value === searchElement) return index;\n current = iterator.next();\n index--;\n }\n\n return -1;\n }\n\n /**\n * Concatenate lists/elements preserving order.\n * @param items - Elements or `LinearBase` instances.\n * @returns New list with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n override concat(...items: LinearBase<E, R>[]): this;\n\n override concat(...items: (E | LinearBase<E, R>)[]): this {\n const newList = this.clone();\n\n for (const item of items) {\n if (item instanceof LinearBase) {\n newList.pushMany(item);\n } else {\n newList.push(item);\n }\n }\n\n return newList;\n }\n\n /**\n * Slice via forward iteration (no random access required).\n * @param start - Inclusive start (supports negative index).\n * @param end - Exclusive end (supports negative index).\n * @returns New list (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n override slice(start: number = 0, end: number = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n const newList = this._createInstance();\n const iterator = this._getIterator();\n let current = iterator.next();\n let c = 0;\n while (c < start) {\n current = iterator.next();\n c++;\n }\n for (let i = start; i < end; i++) {\n newList.push(current.value);\n current = iterator.next();\n }\n\n return newList;\n }\n\n /**\n * Splice by walking node iterators from the start index.\n * @param start - Start index.\n * @param deleteCount - How many elements to remove.\n * @param items - Elements to insert after the splice point.\n * @returns Removed elements as a new list (`this` type).\n * @remarks Time O(n + m), Space O(min(n, m)) where `m = items.length`\n */\n override splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n const removedList = this._createInstance();\n\n start = start < 0 ? this.length + start : start;\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, deleteCount);\n\n let currentIndex = 0;\n let currentNode: NODE | undefined = undefined;\n let previousNode: NODE | undefined = undefined;\n\n const iterator = this._getNodeIterator();\n for (const node of iterator) {\n if (currentIndex === start) {\n currentNode = node;\n break;\n }\n previousNode = node;\n currentIndex++;\n }\n\n for (let i = 0; i < deleteCount && currentNode; i++) {\n removedList.push(currentNode.value);\n const nextNode = currentNode.next;\n this.delete(currentNode);\n currentNode = nextNode as NODE;\n }\n\n for (let i = 0; i < items.length; i++) {\n if (previousNode) {\n this.addAfter(previousNode, items[i]);\n previousNode = previousNode.next as NODE;\n } else {\n this.addAt(0, items[i]);\n previousNode = this._getNodeIterator().next().value;\n }\n }\n\n return removedList;\n }\n\n override reduceRight(callbackfn: ReduceLinearCallback<E>): E;\n\n override reduceRight(callbackfn: ReduceLinearCallback<E>, initialValue: E): E;\n\n /**\n * Right-to-left reduction using reverse iterator.\n * @param callbackfn - `(acc, element, index, self) => acc`.\n * @param initialValue - Initial accumulator.\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n override reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue: U): U;\n\n override reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue?: U): U {\n let accumulator = initialValue ?? (0 as U);\n let index = this.length - 1;\n for (const item of this._getReverseIterator()) {\n accumulator = callbackfn(accumulator, item, index--, this);\n }\n return accumulator;\n }\n\n /**\n * Delete by element or node in a linked list.\n * @param elementOrNode - Element or node.\n * @returns `true` if removed.\n * @remarks Time O(1)~O(n) depending on availability of links, Space O(1)\n */\n abstract override delete(elementOrNode: E | NODE | undefined): boolean;\n\n /**\n * Insert new element/node before an existing node.\n * @param existingElementOrNode - Reference element/node.\n * @param newElementOrNode - Element/node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on reference access, Space O(1)\n */\n abstract addBefore(existingElementOrNode: E | NODE, newElementOrNode: E | NODE): boolean;\n\n /**\n * Insert new element/node after an existing node.\n * @param existingElementOrNode - Reference element/node.\n * @param newElementOrNode - Element/node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on reference access, Space O(1)\n */\n abstract addAfter(existingElementOrNode: E | NODE, newElementOrNode: E | NODE): boolean;\n\n /**\n * Node at index (for random-access emulation).\n * @param index - Position (0-based).\n * @returns Node or `undefined`.\n * @remarks Time O(n), Space O(1)\n */\n abstract getNodeAt(index: number): NODE | undefined;\n\n /**\n * Iterate linked nodes from head to tail.\n * @returns Iterator over nodes.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getNodeIterator(...args: any[]): IterableIterator<NODE>;\n\n /**\n * Get previous node of a given node.\n * @param node - Current node.\n * @returns Previous node or `undefined`.\n * @remarks Time O(1)~O(n) depending on list variant (singly vs doubly), Space O(1)\n */\n protected abstract _getPrevNode(node: NODE): NODE | undefined;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, SinglyLinkedListOptions } from '../../types';\nimport { LinearLinkedBase, LinkedListNode } from '../base/linear-base';\n\n/**\n * Node of a singly linked list; stores value and the next link.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class SinglyLinkedListNode<E = any> extends LinkedListNode<E> {\n /**\n * Create a list node.\n * @remarks Time O(1), Space O(1)\n * @param value - Element value to store.\n * @returns New node instance.\n */\n\n constructor(value: E) {\n super(value);\n this._value = value;\n this._next = undefined;\n }\n\n protected override _next: SinglyLinkedListNode<E> | undefined;\n\n /**\n * Get the next node.\n * @remarks Time O(1), Space O(1)\n * @returns Next node or undefined.\n */\n\n override get next(): SinglyLinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Set the next node.\n * @remarks Time O(1), Space O(1)\n * @param value - Next node or undefined.\n * @returns void\n */\n\n override set next(value: SinglyLinkedListNode<E> | undefined) {\n this._next = value;\n }\n}\n\n/**\n * Singly linked list with O(1) push/pop-like ends operations and linear scans.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.\n * 2. Bidirectional Traversal: Unlike doubly linked lists, singly linked lists can be easily traversed forwards but not backwards.\n * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.\n * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.\n * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).\n * @example\n * // basic SinglyLinkedList creation and push operation\n * // Create a simple SinglyLinkedList with initial values\n * const list = new SinglyLinkedList([1, 2, 3, 4, 5]);\n *\n * // Verify the list maintains insertion order\n * console.log([...list]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(list.length); // 5;\n *\n * // Push a new element to the end\n * list.push(6);\n * console.log(list.length); // 6;\n * console.log([...list]); // [1, 2, 3, 4, 5, 6];\n * @example\n * // SinglyLinkedList pop and shift operations\n * const list = new SinglyLinkedList<number>([10, 20, 30, 40, 50]);\n *\n * // Pop removes from the end\n * const last = list.pop();\n * console.log(last); // 50;\n *\n * // Shift removes from the beginning\n * const first = list.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements\n * console.log([...list]); // [20, 30, 40];\n * console.log(list.length); // 3;\n * @example\n * // SinglyLinkedList unshift and forward traversal\n * const list = new SinglyLinkedList<number>([20, 30, 40]);\n *\n * // Unshift adds to the beginning\n * list.unshift(10);\n * console.log([...list]); // [10, 20, 30, 40];\n *\n * // Access elements (forward traversal only for singly linked)\n * const second = list.at(1);\n * console.log(second); // 20;\n *\n * // SinglyLinkedList allows forward iteration only\n * const elements: number[] = [];\n * for (const item of list) {\n * elements.push(item);\n * }\n * console.log(elements); // [10, 20, 30, 40];\n *\n * console.log(list.length); // 4;\n * @example\n * // SinglyLinkedList filter and map operations\n * const list = new SinglyLinkedList<number>([1, 2, 3, 4, 5]);\n *\n * // Filter even numbers\n * const filtered = list.filter(value => value % 2 === 0);\n * console.log(filtered.length); // 2;\n *\n * // Map to double values\n * const doubled = list.map(value => value * 2);\n * console.log(doubled.length); // 5;\n *\n * // Use reduce to sum\n * const sum = list.reduce((acc, value) => acc + value, 0);\n * console.log(sum); // 15;\n * @example\n * // SinglyLinkedList for sequentially processed data stream\n * interface LogEntry {\n * timestamp: number;\n * level: 'INFO' | 'WARN' | 'ERROR';\n * message: string;\n * }\n *\n * // SinglyLinkedList is ideal for sequential processing where you only need forward iteration\n * // O(1) insertion/deletion at head, O(n) for tail operations\n * const logStream = new SinglyLinkedList<LogEntry>();\n *\n * // Simulate incoming log entries\n * const entries: LogEntry[] = [\n * { timestamp: 1000, level: 'INFO', message: 'Server started' },\n * { timestamp: 1100, level: 'WARN', message: 'Memory usage high' },\n * { timestamp: 1200, level: 'ERROR', message: 'Connection failed' },\n * { timestamp: 1300, level: 'INFO', message: 'Connection restored' }\n * ];\n *\n * // Add entries to the stream\n * for (const entry of entries) {\n * logStream.push(entry);\n * }\n *\n * console.log(logStream.length); // 4;\n *\n * // Process logs sequentially (only forward iteration needed)\n * const processedLogs: string[] = [];\n * for (const log of logStream) {\n * processedLogs.push(`[${log.level}] ${log.message}`);\n * }\n *\n * console.log(processedLogs); // [\n * // '[INFO] Server started',\n * // '[WARN] Memory usage high',\n * // '[ERROR] Connection failed',\n * // '[INFO] Connection restored'\n * // ];\n *\n * // Get first log (O(1) - direct head access)\n * const firstLog = logStream.at(0);\n * console.log(firstLog?.message); // 'Server started';\n *\n * // Remove oldest log (O(1) operation at head)\n * const removed = logStream.shift();\n * console.log(removed?.message); // 'Server started';\n * console.log(logStream.length); // 3;\n *\n * // Remaining logs still maintain order for sequential processing\n * console.log(logStream.length); // 3;\n * @example\n * // implementation of a basic text editor\n * class TextEditor {\n * private content: SinglyLinkedList<string>;\n * private cursorIndex: number;\n * private undoStack: Stack<{ operation: string; data?: any }>;\n *\n * constructor() {\n * this.content = new SinglyLinkedList<string>();\n * this.cursorIndex = 0; // Cursor starts at the beginning\n * this.undoStack = new Stack<{ operation: string; data?: any }>(); // Stack to keep track of operations for undo\n * }\n *\n * insert(char: string) {\n * this.content.addAt(this.cursorIndex, char);\n * this.cursorIndex++;\n * this.undoStack.push({ operation: 'insert', data: { index: this.cursorIndex - 1 } });\n * }\n *\n * delete() {\n * if (this.cursorIndex === 0) return; // Nothing to delete\n * const deleted = this.content.deleteAt(this.cursorIndex - 1);\n * this.cursorIndex--;\n * this.undoStack.push({ operation: 'delete', data: { index: this.cursorIndex, char: deleted } });\n * }\n *\n * moveCursor(index: number) {\n * this.cursorIndex = Math.max(0, Math.min(index, this.content.length));\n * }\n *\n * undo() {\n * if (this.undoStack.size === 0) return; // No operations to undo\n * const lastAction = this.undoStack.pop();\n *\n * if (lastAction!.operation === 'insert') {\n * this.content.deleteAt(lastAction!.data.index);\n * this.cursorIndex = lastAction!.data.index;\n * } else if (lastAction!.operation === 'delete') {\n * this.content.addAt(lastAction!.data.index, lastAction!.data.char);\n * this.cursorIndex = lastAction!.data.index + 1;\n * }\n * }\n *\n * getText(): string {\n * return [...this.content].join('');\n * }\n * }\n *\n * // Example Usage\n * const editor = new TextEditor();\n * editor.insert('H');\n * editor.insert('e');\n * editor.insert('l');\n * editor.insert('l');\n * editor.insert('o');\n * console.log(editor.getText()); // 'Hello'; // Output: \"Hello\"\n *\n * editor.delete();\n * console.log(editor.getText()); // 'Hell'; // Output: \"Hell\"\n *\n * editor.undo();\n * console.log(editor.getText()); // 'Hello'; // Output: \"Hello\"\n *\n * editor.moveCursor(1);\n * editor.insert('a');\n * console.log(editor.getText()); // 'Haello';\n */\nexport class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, SinglyLinkedListNode<E>> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a SinglyLinkedList and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @param [options] - Options such as maxLen and toElementFn.\n * @returns New SinglyLinkedList instance.\n */\n\n constructor(\n elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>> = [],\n options?: SinglyLinkedListOptions<E, R>\n ) {\n super(options);\n this.pushMany(elements);\n }\n\n protected _head: SinglyLinkedListNode<E> | undefined;\n\n /**\n * Get the head node.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or undefined.\n */\n\n get head(): SinglyLinkedListNode<E> | undefined {\n return this._head;\n }\n\n protected _tail: SinglyLinkedListNode<E> | undefined;\n\n /**\n * Get the tail node.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or undefined.\n */\n\n get tail(): SinglyLinkedListNode<E> | undefined {\n return this._tail;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this._length;\n }\n\n /**\n * Get the first element value.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n return this.head?.value;\n }\n\n /**\n * Get the last element value.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n return this.tail?.value;\n }\n\n /**\n * Create a new list from an iterable of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @template S\n * @param this - The constructor (subclass) to instantiate.\n * @param data - Iterable of elements to insert.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new list populated with the iterable's elements.\n */\n\n static from<E, R = any, S extends SinglyLinkedList<E, R> = SinglyLinkedList<E, R>>(\n this: new (\n elements?: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>,\n options?: SinglyLinkedListOptions<E, R>\n ) => S,\n data: Iterable<E>,\n options?: SinglyLinkedListOptions<E, R>\n ): S {\n const list = new this([], options);\n for (const x of data) list.push(x);\n return list;\n }\n\n /**\n * Append an element/node to the tail.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to append.\n * @returns True when appended.\n */\n\n push(elementOrNode: E | SinglyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = this._tail = newNode;\n } else {\n this.tail!.next = newNode;\n this._tail = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the tail element.\n * @remarks Time O(N), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (!this.head) return undefined;\n if (this.head === this.tail) {\n const value = this.head.value;\n this._head = undefined;\n this._tail = undefined;\n this._length--;\n return value;\n }\n let current = this.head;\n while (current.next !== this.tail) current = current.next!;\n const value = this.tail!.value;\n current.next = undefined;\n this._tail = current;\n this._length--;\n return value;\n }\n\n /**\n * Remove and return the head element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (!this.head) return undefined;\n const removed = this.head;\n this._head = this.head.next;\n if (!this._head) this._tail = undefined;\n this._length--;\n return removed.value;\n }\n\n /**\n * Prepend an element/node to the head.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to prepend.\n * @returns True when prepended.\n */\n\n unshift(elementOrNode: E | SinglyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = this._tail = newNode;\n } else {\n newNode.next = this.head;\n this._head = newNode;\n }\n this._length++;\n return true;\n }\n\n /**\n * Append a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E | SinglyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<SinglyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.unshift(this.toElementFn(el as R)));\n else ans.push(this.unshift(el as E | SinglyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Find the first value matching a predicate (by node).\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate to match.\n * @returns Matched value or undefined.\n */\n\n search(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Get the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current!.value;\n }\n\n /**\n * Type guard: check whether the input is a SinglyLinkedListNode.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns True if the value is a SinglyLinkedListNode.\n */\n\n isNode(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is SinglyLinkedListNode<E> {\n return elementNodeOrPredicate instanceof SinglyLinkedListNode;\n }\n\n /**\n * Get the node reference at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Node or undefined.\n */\n\n getNodeAt(index: number): SinglyLinkedListNode<E> | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current;\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n if (index === 0) return this.shift();\n const targetNode = this.getNodeAt(index)!;\n const prevNode = this._getPrevNode(targetNode)!;\n const value = targetNode.value;\n prevNode.next = targetNode.next;\n if (targetNode === this.tail) this._tail = prevNode;\n this._length--;\n return value;\n }\n\n /**\n * Delete the first match by value/node.\n * @remarks Time O(N), Space O(1)\n * @param [elementOrNode] - Element or node to remove; if omitted/undefined, nothing happens.\n * @returns True if removed.\n */\n\n delete(elementOrNode: E | SinglyLinkedListNode<E> | undefined): boolean {\n if (elementOrNode === undefined || !this.head) return false;\n const node = this.isNode(elementOrNode) ? elementOrNode : this.getNode(elementOrNode);\n if (!node) return false;\n const prevNode = this._getPrevNode(node);\n\n if (!prevNode) {\n this._head = node.next;\n if (node === this.tail) this._tail = undefined;\n } else {\n prevNode.next = node.next;\n if (node === this.tail) this._tail = prevNode;\n }\n this._length--;\n return true;\n }\n\n /**\n * Insert a new element/node at an index, shifting following nodes.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElementOrNode: E | SinglyLinkedListNode<E>): boolean {\n if (index < 0 || index > this._length) return false;\n if (index === 0) return this.unshift(newElementOrNode);\n if (index === this._length) return this.push(newElementOrNode);\n const newNode = this._ensureNode(newElementOrNode);\n const prevNode = this.getNodeAt(index - 1)!;\n newNode.next = prevNode.next;\n prevNode.next = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Set the element value at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param value - New value.\n * @returns True if updated.\n */\n\n setAt(index: number, value: E): boolean {\n const node = this.getNodeAt(index);\n if (!node) return false;\n node.value = value;\n return true;\n }\n\n /**\n * Check whether the list is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this._length === 0;\n }\n\n /**\n * Remove all nodes and reset length.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n }\n\n /**\n * Reverse the list in place.\n * @remarks Time O(N), Space O(1)\n * @returns This list.\n */\n\n reverse(): this {\n if (!this.head || this.head === this.tail) return this;\n let prev: SinglyLinkedListNode<E> | undefined;\n let current: SinglyLinkedListNode<E> | undefined = this.head;\n let next: SinglyLinkedListNode<E> | undefined;\n while (current) {\n next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n [this._head, this._tail] = [this.tail!, this.head!];\n return this;\n }\n\n /**\n * Find a node by value, reference, or predicate.\n * @remarks Time O(N), Space O(1)\n * @param [elementNodeOrPredicate] - Element, node, or node predicate to match.\n * @returns Matching node or undefined.\n */\n\n getNode(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean) | undefined\n ): SinglyLinkedListNode<E> | undefined {\n if (elementNodeOrPredicate === undefined) return;\n if (this.isNode(elementNodeOrPredicate)) return elementNodeOrPredicate;\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Insert a new element/node before an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addBefore(\n existingElementOrNode: E | SinglyLinkedListNode<E>,\n newElementOrNode: E | SinglyLinkedListNode<E>\n ): boolean {\n const existingNode = this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n const prevNode = this._getPrevNode(existingNode);\n const newNode = this._ensureNode(newElementOrNode);\n\n if (!prevNode) {\n newNode.next = this._head;\n this._head = newNode;\n if (!this._tail) this._tail = newNode;\n this._length++;\n } else {\n prevNode.next = newNode;\n newNode.next = existingNode;\n this._length++;\n }\n return true;\n }\n\n /**\n * Insert a new element/node after an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAfter(existingElementOrNode: E | SinglyLinkedListNode<E>, newElementOrNode: E | SinglyLinkedListNode<E>): boolean {\n const existingNode = this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n const newNode = this._ensureNode(newElementOrNode);\n newNode.next = existingNode.next;\n existingNode.next = newNode;\n if (existingNode === this.tail) this._tail = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Remove and/or insert elements at a position (array-like behavior).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default 0).\n * @param [items] - Elements to insert after `start`.\n * @returns A new list containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount = 0, ...items: E[]): this {\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, deleteCount);\n\n const removedList = this._createInstance();\n\n const prevNode = start === 0 ? undefined : this.getNodeAt(start - 1);\n let cur = prevNode ? prevNode.next : this.head;\n\n let removedCount = 0;\n while (removedCount < deleteCount && cur) {\n removedList.push(cur.value);\n cur = cur.next;\n removedCount++;\n }\n const afterNode = cur;\n\n if (prevNode) {\n prevNode.next = afterNode;\n } else {\n this._head = afterNode;\n }\n if (!afterNode) this._tail = prevNode;\n\n if (items.length > 0) {\n let firstInserted: SinglyLinkedListNode<E> | undefined;\n let lastInserted: SinglyLinkedListNode<E> | undefined;\n for (const it of items) {\n const node = this._ensureNode(it);\n if (!firstInserted) firstInserted = node;\n if (lastInserted) lastInserted.next = node;\n lastInserted = node;\n }\n if (prevNode) prevNode.next = firstInserted!;\n else this._head = firstInserted!;\n\n lastInserted!.next = afterNode;\n if (!afterNode) this._tail = lastInserted!;\n }\n\n this._length += items.length - removedCount;\n if (this._length === 0) {\n this._head = undefined;\n this._tail = undefined;\n }\n\n return removedList as unknown as this;\n }\n\n /**\n * Count how many nodes match a value/node/predicate.\n * @remarks Time O(N), Space O(1)\n * @param elementOrNode - Element, node, or node predicate to match.\n * @returns Number of matches in the list.\n */\n\n countOccurrences(elementOrNode: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)): number {\n const predicate = elementOrPredicate(elementOrNode, this._equals);\n let count = 0;\n let current = this.head;\n while (current) {\n if (predicate(current)) count++;\n current = current.next;\n }\n return count;\n }\n\n /**\n * Set the equality comparator used to compare values.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This list.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Delete the first node whose value matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Predicate (value, index, list) → boolean to decide deletion.\n * @returns True if a node was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, list: this) => boolean): boolean {\n let prev: SinglyLinkedListNode<E> | undefined;\n let current = this.head;\n let i = 0;\n while (current) {\n if (predicate(current.value, i++, this)) {\n if (!prev) {\n this._head = current.next;\n if (current === this._tail) this._tail = undefined;\n } else {\n prev.next = current.next;\n if (current === this._tail) this._tail = prev;\n }\n this._length--;\n return true;\n }\n prev = current;\n current = current.next;\n }\n return false;\n }\n\n /**\n * Deep clone this list (values are copied by reference).\n * @remarks Time O(N), Space O(N)\n * @returns A new list with the same element sequence.\n */\n\n clone(): this {\n const out = this._createInstance();\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Predicate (value, index, list) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with kept values.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance();\n let index = 0;\n for (const value of this) if (callback.call(thisArg, value, index++, this)) out.push(value);\n return out;\n }\n\n /**\n * Map values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, list) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance();\n let index = 0;\n for (const value of this) {\n const mv = thisArg === undefined ? callback(value, index++, this) : callback.call(thisArg, value, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new list (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, list) → newElement.\n * @param [options] - Options for the output list (e.g., maxLen, toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new SinglyLinkedList with mapped values.\n */\n\n map<EM, RM = any>(\n callback: ElementCallback<E, R, EM>,\n options?: SinglyLinkedListOptions<EM, RM>,\n thisArg?: any\n ): SinglyLinkedList<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}), maxLen: this._maxLen as number });\n let index = 0;\n for (const value of this) out.push(callback.call(thisArg, value, index++, this));\n return out;\n }\n\n /**\n * (Protected) Create a node from a value.\n * @remarks Time O(1), Space O(1)\n * @param value - Value to wrap in a node.\n * @returns A new SinglyLinkedListNode instance.\n */\n\n protected createNode(value: E): SinglyLinkedListNode<E> {\n return new SinglyLinkedListNode<E>(value);\n }\n\n /**\n * (Protected) Check if input is a node predicate function.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate.\n * @returns True if input is a predicate function.\n */\n\n protected _isPredicate(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is (node: SinglyLinkedListNode<E>) => boolean {\n return typeof elementNodeOrPredicate === 'function';\n }\n\n /**\n * (Protected) Normalize input into a node instance.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node.\n * @returns A SinglyLinkedListNode for the provided input.\n */\n\n protected _ensureNode(elementOrNode: E | SinglyLinkedListNode<E>) {\n if (this.isNode(elementOrNode)) return elementOrNode;\n return this.createNode(elementOrNode);\n }\n\n /**\n * (Protected) Normalize input into a node predicate.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns A predicate taking a node and returning true/false.\n */\n\n protected _ensurePredicate(\n elementNodeOrPredicate: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean)\n ) {\n if (this.isNode(elementNodeOrPredicate)) return (node: SinglyLinkedListNode<E>) => node === elementNodeOrPredicate;\n if (this._isPredicate(elementNodeOrPredicate)) return elementNodeOrPredicate;\n const value = elementNodeOrPredicate as E;\n return (node: SinglyLinkedListNode<E>) => this._equals(node.value, value);\n }\n\n /**\n * (Protected) Get the previous node of a given node.\n * @remarks Time O(N), Space O(1)\n * @param node - A node in the list.\n * @returns Previous node or undefined.\n */\n\n protected _getPrevNode(node: SinglyLinkedListNode<E>): SinglyLinkedListNode<E> | undefined {\n if (!this.head || this.head === node) return undefined;\n let current = this.head;\n while (current.next && current.next !== node) current = current.next;\n return current.next === node ? current : undefined;\n }\n\n /**\n * (Protected) Iterate values from head to tail.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of values (E).\n */\n\n protected *_getIterator(): IterableIterator<E> {\n let current = this.head;\n while (current) {\n yield current.value;\n current = current.next;\n }\n }\n\n /**\n * (Protected) Iterate values from tail to head.\n * @remarks Time O(N), Space O(N)\n * @returns Iterator of values (E).\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n const reversedArr = [...this].reverse();\n for (const item of reversedArr) yield item;\n }\n\n /**\n * (Protected) Iterate nodes from head to tail.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of nodes.\n */\n\n protected *_getNodeIterator(): IterableIterator<SinglyLinkedListNode<E>> {\n let current = this.head;\n while (current) {\n yield current;\n current = current.next;\n }\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind list instance.\n */\n\n protected _createInstance(options?: SinglyLinkedListOptions<E, R>): this {\n const Ctor: any = this.constructor;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new list.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind SinglyLinkedList instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> | Iterable<SinglyLinkedListNode<EM>> = [],\n options?: SinglyLinkedListOptions<EM, RM>\n ): SinglyLinkedList<EM, RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as SinglyLinkedList<EM, RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind list instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind SinglyLinkedList instance.\n */\n\n protected _spawnLike<EM, RM>(options?: SinglyLinkedListOptions<EM, RM>): SinglyLinkedList<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\nfunction elementOrPredicate<E>(\n input: E | SinglyLinkedListNode<E> | ((node: SinglyLinkedListNode<E>) => boolean),\n equals: (a: E, b: E) => boolean\n) {\n if (input instanceof SinglyLinkedListNode) return (node: SinglyLinkedListNode<E>) => node === input;\n if (typeof input === 'function') return input as (node: SinglyLinkedListNode<E>) => boolean;\n const value = input as E;\n return (node: SinglyLinkedListNode<E>) => equals(node.value, value);\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { DoublyLinkedListOptions, ElementCallback, LinearBaseOptions } from '../../types';\nimport { LinearLinkedBase, LinkedListNode } from '../base/linear-base';\n\n/**\n * Node of a doubly linked list; stores value and prev/next links.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class DoublyLinkedListNode<E = any> extends LinkedListNode<E> {\n /**\n * Create a node.\n * @remarks Time O(1), Space O(1)\n * @param value - Element value to store.\n * @returns New node instance.\n */\n\n constructor(value: E) {\n super(value);\n this._value = value;\n this._next = undefined;\n this._prev = undefined;\n }\n\n protected override _next: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the next node link.\n * @remarks Time O(1), Space O(1)\n * @returns Next node or undefined.\n */\n\n override get next(): DoublyLinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Set the next node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Next node or undefined.\n * @returns void\n */\n\n override set next(value: DoublyLinkedListNode<E> | undefined) {\n this._next = value;\n }\n\n protected _prev: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the previous node link.\n * @remarks Time O(1), Space O(1)\n * @returns Previous node or undefined.\n */\n\n get prev(): DoublyLinkedListNode<E> | undefined {\n return this._prev;\n }\n\n /**\n * Set the previous node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Previous node or undefined.\n * @returns void\n */\n\n set prev(value: DoublyLinkedListNode<E> | undefined) {\n this._prev = value;\n }\n}\n\n/**\n * Doubly linked list with O(1) push/pop/unshift/shift and linear scans.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.\n * 2. Bidirectional Traversal: Unlike singly linked lists, doubly linked lists can be easily traversed forwards or backwards. This makes insertions and deletions in the list more flexible and efficient.\n * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.\n * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.\n * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).\n * @example\n * // basic DoublyLinkedList creation and push operation\n * // Create a simple DoublyLinkedList with initial values\n * const list = new DoublyLinkedList([1, 2, 3, 4, 5]);\n *\n * // Verify the list maintains insertion order\n * console.log([...list]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(list.length); // 5;\n *\n * // Push a new element to the end\n * list.push(6);\n * console.log(list.length); // 6;\n * console.log([...list]); // [1, 2, 3, 4, 5, 6];\n * @example\n * // DoublyLinkedList pop and shift operations\n * const list = new DoublyLinkedList<number>([10, 20, 30, 40, 50]);\n *\n * // Pop removes from the end\n * const last = list.pop();\n * console.log(last); // 50;\n *\n * // Shift removes from the beginning\n * const first = list.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements\n * console.log([...list]); // [20, 30, 40];\n * console.log(list.length); // 3;\n * @example\n * // DoublyLinkedList for...of iteration and map operation\n * const list = new DoublyLinkedList<number>([1, 2, 3, 4, 5]);\n *\n * // Iterate through list\n * const doubled = list.map(value => value * 2);\n * console.log(doubled.length); // 5;\n *\n * // Use for...of loop\n * const result: number[] = [];\n * for (const item of list) {\n * result.push(item);\n * }\n * console.log(result); // [1, 2, 3, 4, 5];\n * @example\n * // Browser history\n * const browserHistory = new DoublyLinkedList<string>();\n *\n * browserHistory.push('home page');\n * browserHistory.push('search page');\n * browserHistory.push('details page');\n *\n * console.log(browserHistory.last); // 'details page';\n * console.log(browserHistory.pop()); // 'details page';\n * console.log(browserHistory.last); // 'search page';\n * @example\n * // DoublyLinkedList for LRU cache implementation\n * interface CacheEntry {\n * key: string;\n * value: string;\n * }\n *\n * // Simulate LRU cache using DoublyLinkedList\n * // DoublyLinkedList is perfect because:\n * // - O(1) delete from any position\n * // - O(1) push to end\n * // - Bidirectional traversal for LRU policy\n *\n * const cacheList = new DoublyLinkedList<CacheEntry>();\n * const maxSize = 3;\n *\n * // Add cache entries\n * cacheList.push({ key: 'user:1', value: 'Alice' });\n * cacheList.push({ key: 'user:2', value: 'Bob' });\n * cacheList.push({ key: 'user:3', value: 'Charlie' });\n *\n * // Try to add a new entry when cache is full\n * if (cacheList.length >= maxSize) {\n * // Remove the oldest (first) entry\n * const evicted = cacheList.shift();\n * console.log(evicted?.key); // 'user:1';\n * }\n *\n * // Add new entry\n * cacheList.push({ key: 'user:4', value: 'Diana' });\n *\n * // Verify current cache state\n * console.log(cacheList.length); // 3;\n * const cachedKeys = [...cacheList].map(entry => entry.key);\n * console.log(cachedKeys); // ['user:2', 'user:3', 'user:4'];\n *\n * // Access entry (in real LRU, this would move it to end)\n * const foundEntry = [...cacheList].find(entry => entry.key === 'user:2');\n * console.log(foundEntry?.value); // 'Bob';\n */\nexport class DoublyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, DoublyLinkedListNode<E>> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a DoublyLinkedList and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @param [options] - Options such as maxLen and toElementFn.\n * @returns New DoublyLinkedList instance.\n */\n\n constructor(\n elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>> = [],\n options?: DoublyLinkedListOptions<E, R>\n ) {\n super(options);\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n\n if (options?.maxLen && Number.isInteger(options.maxLen) && options.maxLen > 0) {\n this._maxLen = options.maxLen;\n }\n\n this.pushMany(elements);\n }\n\n protected _head: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the head node.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or undefined.\n */\n\n get head(): DoublyLinkedListNode<E> | undefined {\n return this._head;\n }\n\n protected _tail: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the tail node.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or undefined.\n */\n\n get tail(): DoublyLinkedListNode<E> | undefined {\n return this._tail;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this._length;\n }\n\n /**\n * Get the first element value.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n return this.head?.value;\n }\n\n /**\n * Get the last element value.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n return this.tail?.value;\n }\n\n /**\n * Create a new list from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param data - Array of elements to insert.\n * @returns A new list populated with the array's elements.\n */\n\n static fromArray<E, R = any>(\n this: new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => any,\n data: E[]\n ) {\n return new this(data);\n }\n\n /**\n * Type guard: check whether the input is a DoublyLinkedListNode.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns True if the value is a DoublyLinkedListNode.\n */\n\n isNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is DoublyLinkedListNode<E> {\n return elementNodeOrPredicate instanceof DoublyLinkedListNode;\n }\n\n /**\n * Append an element/node to the tail.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to append.\n * @returns True when appended.\n */\n\n push(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.prev = this.tail;\n this.tail!.next = newNode;\n this._tail = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the tail element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (!this.tail) return undefined;\n const removed = this.tail;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._tail = removed.prev;\n this.tail!.next = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Remove and return the head element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (!this.head) return undefined;\n const removed = this.head;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._head = removed.next;\n this.head!.prev = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Prepend an element/node to the head.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to prepend.\n * @returns True when prepended.\n */\n\n unshift(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.next = this.head;\n this.head!.prev = newNode;\n this._head = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this._length > this._maxLen) this.pop();\n return true;\n }\n\n /**\n * Append a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.unshift(this.toElementFn(el as R)));\n else ans.push(this.unshift(el as E | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Get the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current!.value;\n }\n\n /**\n * Get the node reference at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Node or undefined.\n */\n\n getNodeAt(index: number): DoublyLinkedListNode<E> | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current;\n }\n\n /**\n * Find a node by value, reference, or predicate.\n * @remarks Time O(N), Space O(1)\n * @param [elementNodeOrPredicate] - Element, node, or predicate to match.\n * @returns Matching node or undefined.\n */\n\n getNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean) | undefined\n ): DoublyLinkedListNode<E> | undefined {\n if (elementNodeOrPredicate === undefined) return;\n\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n\n let cur = this.head;\n while (cur) {\n if (cur === target) return target;\n cur = cur.next;\n }\n\n const isMatch = (node: DoublyLinkedListNode<E>) => this._equals(node.value, target.value);\n cur = this.head;\n while (cur) {\n if (isMatch(cur)) return cur;\n cur = cur.next;\n }\n return undefined;\n }\n\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Insert a new element/node at an index, shifting following nodes.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n if (index < 0 || index > this._length) return false;\n if (index === 0) return this.unshift(newElementOrNode);\n if (index === this._length) return this.push(newElementOrNode);\n\n const newNode = this._ensureNode(newElementOrNode);\n const prevNode = this.getNodeAt(index - 1)!;\n const nextNode = prevNode.next!;\n newNode.prev = prevNode;\n newNode.next = nextNode;\n prevNode.next = newNode;\n nextNode.prev = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node before an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addBefore(\n existingElementOrNode: E | DoublyLinkedListNode<E>,\n newElementOrNode: E | DoublyLinkedListNode<E>\n ): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.prev = existingNode.prev;\n if (existingNode.prev) existingNode.prev.next = newNode;\n newNode.next = existingNode;\n existingNode.prev = newNode;\n if (existingNode === this.head) this._head = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node after an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAfter(existingElementOrNode: E | DoublyLinkedListNode<E>, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.next = existingNode.next;\n if (existingNode.next) existingNode.next.prev = newNode;\n newNode.prev = existingNode;\n existingNode.next = newNode;\n if (existingNode === this.tail) this._tail = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Set the element value at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param value - New value.\n * @returns True if updated.\n */\n\n setAt(index: number, value: E): boolean {\n const node = this.getNodeAt(index);\n if (!node) return false;\n node.value = value;\n return true;\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this._length) return;\n if (index === 0) return this.shift();\n if (index === this._length - 1) return this.pop();\n\n const removedNode = this.getNodeAt(index)!;\n const prevNode = removedNode.prev!;\n const nextNode = removedNode.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n return removedNode.value;\n }\n\n /**\n * Delete the first match by value/node.\n * @remarks Time O(N), Space O(1)\n * @param [elementOrNode] - Element or node to remove.\n * @returns True if removed.\n */\n\n delete(elementOrNode: E | DoublyLinkedListNode<E> | undefined): boolean {\n const node = this.getNode(elementOrNode);\n if (!node) return false;\n\n if (node === this.head) this.shift();\n else if (node === this.tail) this.pop();\n else {\n const prevNode = node.prev!;\n const nextNode = node.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n }\n return true;\n }\n\n /**\n * Check whether the list is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this._length === 0;\n }\n\n /**\n * Remove all nodes and reset length.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n }\n\n /**\n * Find the first value matching a predicate scanning forward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n search(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Find the first value matching a predicate scanning backward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n getBackward(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.tail;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.prev;\n }\n return undefined;\n }\n\n /**\n * Reverse the list in place.\n * @remarks Time O(N), Space O(1)\n * @returns This list.\n */\n\n reverse(): this {\n let current = this.head;\n [this._head, this._tail] = [this.tail, this.head];\n while (current) {\n const next = current.next;\n [current.prev, current.next] = [current.next, current.prev];\n current = next;\n }\n return this;\n }\n\n /**\n * Set the equality comparator used to compare values.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This list.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Deep clone this list (values are copied by reference).\n * @remarks Time O(N), Space O(N)\n * @returns A new list with the same element sequence.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Predicate (value, index, list) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with kept values.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) if (callback.call(thisArg, v, index++, this)) out.push(v);\n return out;\n }\n\n /**\n * Map values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, list) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new list (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, list) → newElement.\n * @param [options] - Options for the output list (e.g., maxLen, toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new DoublyLinkedList with mapped values.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: DoublyLinkedListOptions<EM, RM>,\n thisArg?: any\n ): DoublyLinkedList<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}), maxLen: this._maxLen });\n let index = 0;\n for (const v of this) out.push(callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * (Protected) Create or return a node for the given input (node or raw element).\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element value or node to normalize.\n * @returns A DoublyLinkedListNode for the provided input.\n */\n\n protected _ensureNode(elementOrNode: E | DoublyLinkedListNode<E>) {\n if (this.isNode(elementOrNode)) return elementOrNode;\n return new DoublyLinkedListNode<E>(elementOrNode);\n }\n\n /**\n * (Protected) Normalize input into a predicate over nodes.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate.\n * @returns A predicate function taking a node and returning true/false.\n */\n\n protected _ensurePredicate(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): (node: DoublyLinkedListNode<E>) => boolean {\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n return (node: DoublyLinkedListNode<E>) => node === target;\n }\n if (typeof elementNodeOrPredicate === 'function') {\n return elementNodeOrPredicate as (node: DoublyLinkedListNode<E>) => boolean;\n }\n const value = elementNodeOrPredicate as E;\n return (node: DoublyLinkedListNode<E>) => this._equals(node.value, value);\n }\n\n /**\n * (Protected) Get the previous node of a given node.\n * @remarks Time O(1), Space O(1)\n * @param node - A node in the list.\n * @returns Previous node or undefined.\n */\n\n protected _getPrevNode(node: DoublyLinkedListNode<E>): DoublyLinkedListNode<E> | undefined {\n return node.prev;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind list instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => this;\n return new Ctor([], options as DoublyLinkedListOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new list.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind DoublyLinkedList instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>> = [],\n options?: DoublyLinkedListOptions<EM, RM>\n ): DoublyLinkedList<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>>,\n options?: DoublyLinkedListOptions<EM, RM>\n ) => DoublyLinkedList<EM, RM>;\n return new Ctor(elements, options);\n }\n\n protected *_getIterator(): IterableIterator<E> {\n let current = this.head;\n while (current) {\n yield current.value;\n current = current.next;\n }\n }\n\n protected *_getReverseIterator(): IterableIterator<E> {\n let current = this.tail;\n while (current) {\n yield current.value;\n current = current.prev;\n }\n }\n\n protected *_getNodeIterator(): IterableIterator<DoublyLinkedListNode<E>> {\n let current = this.head;\n while (current) {\n yield current;\n current = current.next;\n }\n }\n}\n","import type { SkipLinkedListOptions } from '../../types';\n\nexport class SkipListNode<K, V> {\n key: K;\n value: V;\n forward: SkipListNode<K, V>[];\n\n constructor(key: K, value: V, level: number) {\n this.key = key;\n this.value = value;\n this.forward = new Array(level);\n }\n}\n\nexport class SkipList<K, V> {\n constructor(elements: Iterable<[K, V]> = [], options?: SkipLinkedListOptions) {\n if (options) {\n const { maxLevel, probability } = options;\n if (typeof maxLevel === 'number') this._maxLevel = maxLevel;\n if (typeof probability === 'number') this._probability = probability;\n }\n\n if (elements) {\n for (const [key, value] of elements) this.add(key, value);\n }\n }\n\n protected _head: SkipListNode<K, V> = new SkipListNode<K, V>(undefined as K, undefined as V, this.maxLevel);\n\n get head(): SkipListNode<K, V> {\n return this._head;\n }\n\n protected _level: number = 0;\n\n get level(): number {\n return this._level;\n }\n\n protected _maxLevel: number = 16;\n\n get maxLevel(): number {\n return this._maxLevel;\n }\n\n protected _probability: number = 0.5;\n\n get probability(): number {\n return this._probability;\n }\n\n get first(): V | undefined {\n const firstNode = this.head.forward[0];\n return firstNode ? firstNode.value : undefined;\n }\n\n get last(): V | undefined {\n let current = this.head;\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i]) {\n current = current.forward[i];\n }\n }\n return current.value;\n }\n\n add(key: K, value: V): void {\n const newNode = new SkipListNode(key, value, this._randomLevel());\n const update: SkipListNode<K, V>[] = new Array(this.maxLevel).fill(this.head);\n let current = this.head;\n\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n update[i] = current;\n }\n\n for (let i = 0; i < newNode.forward.length; i++) {\n newNode.forward[i] = update[i].forward[i];\n update[i].forward[i] = newNode;\n }\n\n if (!newNode.forward[0]) {\n this._level = Math.max(this.level, newNode.forward.length);\n }\n }\n\n get(key: K): V | undefined {\n let current = this.head;\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n }\n\n current = current.forward[0];\n\n if (current && current.key === key) {\n return current.value;\n }\n\n return undefined;\n }\n\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n delete(key: K): boolean {\n const update: SkipListNode<K, V>[] = new Array(this.maxLevel).fill(this.head);\n let current = this.head;\n\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n update[i] = current;\n }\n\n current = current.forward[0];\n\n if (current && current.key === key) {\n for (let i = 0; i < this.level; i++) {\n if (update[i].forward[i] !== current) {\n break;\n }\n update[i].forward[i] = current.forward[i];\n }\n while (this.level > 0 && !this.head.forward[this.level - 1]) {\n this._level--;\n }\n return true;\n }\n\n return false;\n }\n\n higher(key: K): V | undefined {\n let current = this.head;\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key <= key) {\n current = current.forward[i];\n }\n }\n const nextNode = current.forward[0];\n return nextNode ? nextNode.value : undefined;\n }\n\n lower(key: K): V | undefined {\n let current = this.head;\n let lastLess = undefined;\n\n for (let i = this.level - 1; i >= 0; i--) {\n while (current.forward[i] && current.forward[i].key < key) {\n current = current.forward[i];\n }\n if (current.key < key) {\n lastLess = current;\n }\n }\n\n return lastLess ? lastLess.value : undefined;\n }\n\n protected _randomLevel(): number {\n let level = 1;\n while (Math.random() < this.probability && level < this.maxLevel) {\n level++;\n }\n return level;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, IterableElementBaseOptions, StackOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * LIFO stack with array storage and optional record→element conversion.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Last In, First Out (LIFO): The core characteristic of a stack is its last in, first out nature, meaning the last element added to the stack will be the first to be removed.\n * 2. Uses: Stacks are commonly used for managing a series of tasks or elements that need to be processed in a last in, first out manner. They are widely used in various scenarios, such as in function calls in programming languages, evaluation of arithmetic expressions, and backtracking algorithms.\n * 3. Performance: Stack operations are typically O(1) in time complexity, meaning that regardless of the stack's size, adding, removing, and viewing the top element are very fast operations.\n * 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.\n * 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.\n * 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.\n * @example\n * // basic Stack creation and push operation\n * // Create a simple Stack with initial values\n * const stack = new Stack([1, 2, 3, 4, 5]);\n *\n * // Verify the stack maintains insertion order (LIFO will be shown in pop)\n * console.log([...stack]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(stack.size); // 5;\n *\n * // Push a new element to the top\n * stack.push(6);\n * console.log(stack.size); // 6;\n * @example\n * // Stack pop operation (LIFO - Last In First Out)\n * const stack = new Stack<number>([10, 20, 30, 40, 50]);\n *\n * // Peek at the top element without removing\n * const top = stack.peek();\n * console.log(top); // 50;\n *\n * // Pop removes from the top (LIFO order)\n * const popped = stack.pop();\n * console.log(popped); // 50;\n *\n * // Next pop gets the previous element\n * const next = stack.pop();\n * console.log(next); // 40;\n *\n * // Verify length decreased\n * console.log(stack.size); // 3;\n * @example\n * // Function Call Stack\n * const functionStack = new Stack<string>();\n * functionStack.push('main');\n * functionStack.push('foo');\n * functionStack.push('bar');\n * console.log(functionStack.pop()); // 'bar';\n * console.log(functionStack.pop()); // 'foo';\n * console.log(functionStack.pop()); // 'main';\n * @example\n * // Balanced Parentheses or Brackets\n * type ValidCharacters = ')' | '(' | ']' | '[' | '}' | '{';\n *\n * const stack = new Stack<string>();\n * const input: ValidCharacters[] = '[({})]'.split('') as ValidCharacters[];\n * const matches: { [key in ValidCharacters]?: ValidCharacters } = { ')': '(', ']': '[', '}': '{' };\n * for (const char of input) {\n * if ('([{'.includes(char)) {\n * stack.push(char);\n * } else if (')]}'.includes(char)) {\n * if (stack.pop() !== matches[char]) {\n * fail('Parentheses are not balanced');\n * }\n * }\n * }\n * console.log(stack.isEmpty()); // true;\n * @example\n * // Expression Evaluation and Conversion\n * const stack = new Stack<number>();\n * const expression = [5, 3, '+']; // Equivalent to 5 + 3\n * expression.forEach(token => {\n * if (typeof token === 'number') {\n * stack.push(token);\n * } else {\n * const b = stack.pop()!;\n * const a = stack.pop()!;\n * stack.push(token === '+' ? a + b : 0); // Only handling '+' here\n * }\n * });\n * console.log(stack.pop()); // 8;\n * @example\n * // Backtracking Algorithms\n * const stack = new Stack<[number, number]>();\n * const maze = [\n * ['S', ' ', 'X'],\n * ['X', ' ', 'X'],\n * [' ', ' ', 'E']\n * ];\n * const start: [number, number] = [0, 0];\n * const end = [2, 2];\n * const directions = [\n * [0, 1], // To the right\n * [1, 0], // down\n * [0, -1], // left\n * [-1, 0] // up\n * ];\n *\n * const visited = new Set<string>(); // Used to record visited nodes\n * stack.push(start);\n * const path: number[][] = [];\n *\n * while (!stack.isEmpty()) {\n * const [x, y] = stack.pop()!;\n * if (visited.has(`${x},${y}`)) continue; // Skip already visited nodes\n * visited.add(`${x},${y}`);\n *\n * path.push([x, y]);\n *\n * if (x === end[0] && y === end[1]) {\n * break; // Find the end point and exit\n * }\n *\n * for (const [dx, dy] of directions) {\n * const nx = x + dx;\n * const ny = y + dy;\n * if (\n * maze[nx]?.[ny] === ' ' || // feasible path\n * maze[nx]?.[ny] === 'E' // destination\n * ) {\n * stack.push([nx, ny]);\n * }\n * }\n * }\n *\n * console.log(path); // contains end;\n * @example\n * // Stock Span Problem\n * const stack = new Stack<number>();\n * const prices = [100, 80, 60, 70, 60, 75, 85];\n * const spans: number[] = [];\n * prices.forEach((price, i) => {\n * while (!stack.isEmpty() && prices[stack.peek()!] <= price) {\n * stack.pop();\n * }\n * spans.push(stack.isEmpty() ? i + 1 : i - stack.peek()!);\n * stack.push(i);\n * });\n * console.log(spans); // [1, 1, 1, 2, 1, 4, 6];\n * @example\n * // Simplify File Paths\n * const stack = new Stack<string>();\n * const path = '/a/./b/../../c';\n * path.split('/').forEach(segment => {\n * if (segment === '..') stack.pop();\n * else if (segment && segment !== '.') stack.push(segment);\n * });\n * console.log(stack.elements.join('/')); // 'c';\n */\nexport class Stack<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a Stack and optionally bulk-push elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn and equality function.\n * @returns New Stack instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: StackOptions<E, R>) {\n super(options);\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of stored elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Create a stack from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param elements - Array of elements to push in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Stack populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => any,\n elements: E[],\n options?: StackOptions<E, R>\n ) {\n return new this(elements, options);\n }\n\n /**\n * Check whether the stack is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.elements.length === 0;\n }\n\n /**\n * Get the top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.isEmpty() ? undefined : this.elements[this.elements.length - 1];\n }\n\n /**\n * Push one element onto the top.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to push.\n * @returns True when pushed.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n return true;\n }\n\n /**\n * Pop and return the top element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n return this.isEmpty() ? undefined : this.elements.pop();\n }\n\n /**\n * Push many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx);\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the bottom.\n * @returns True if removed.\n */\n\n deleteAt(index: number): boolean {\n if (index < 0 || index >= this.elements.length) return false;\n const spliced = this.elements.splice(index, 1);\n return spliced.length === 1;\n }\n\n /**\n * Delete the first element that satisfies a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, stack) → boolean to decide deletion.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, stack: this) => boolean): boolean {\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Remove all elements and reset storage.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Deep clone this stack.\n * @remarks Time O(N), Space O(N)\n * @returns A new stack with the same content.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter elements into a new stack of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, stack) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new stack with kept values.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map values into a new stack of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, stack) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new stack with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new stack (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, stack) → newElement.\n * @param [options] - Options for the output stack (e.g., toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Stack with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): Stack<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}) });\n let index = 0;\n for (const v of this) {\n out.push(thisArg === undefined ? callback(v, index, this) : callback.call(thisArg, v, index, this));\n index++;\n }\n return out;\n }\n\n /**\n * Set the equality comparator used by delete/search operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This stack.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * (Protected) Find the index of a target element using the equality function.\n * @remarks Time O(N), Space O(1)\n * @param target - Element to search for.\n * @returns Index or -1 if not found.\n */\n\n protected _indexOfByEquals(target: E): number {\n for (let i = 0; i < this.elements.length; i++) if (this._equals(this.elements[i], target)) return i;\n return -1;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind stack instance.\n */\n\n protected _createInstance(options?: StackOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => this;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind stack and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new stack.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Stack instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: Iterable<T> | Iterable<RR> = [],\n options?: StackOptions<T, RR>\n ): Stack<T, RR> {\n const Ctor = this.constructor as new (\n elements?: Iterable<T> | Iterable<RR>,\n options?: StackOptions<T, RR>\n ) => Stack<T, RR>;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from bottom to top.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this.elements.length; i++) yield this.elements[i];\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, LinearBaseOptions, QueueOptions } from '../../types';\nimport { SinglyLinkedList } from '../linked-list';\nimport { LinearBase } from '../base/linear-base';\n\n/**\n * Array-backed queue with amortized O(1) enqueue/dequeue via an offset pointer and optional auto-compaction.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. First In, First Out (FIFO): The core feature of a queue is its first in, first out nature. The element added to the queue first will be the one to be removed first.\n * 2. Operations: The main operations include enqueue (adding an element to the end of the queue) and dequeue (removing and returning the element at the front of the queue). Typically, there is also a peek operation (looking at the front element without removing it).\n * 3. Uses: Queues are commonly used to manage a series of tasks or elements that need to be processed in order. For example, managing task queues in a multi-threaded environment, or in algorithms for data structures like trees and graphs for breadth-first search.\n * 4. Task Scheduling: Managing the order of task execution in operating systems or applications.\n * 5. Data Buffering: Acting as a buffer for data packets in network communication.\n * 6. Breadth-First Search (BFS): In traversal algorithms for graphs and trees, queues store elements that are to be visited.\n * 7. Real-time Queuing: Like queuing systems in banks or supermarkets.\n * @example\n * // basic Queue creation and push operation\n * // Create a simple Queue with initial values\n * const queue = new Queue([1, 2, 3, 4, 5]);\n *\n * // Verify the queue maintains insertion order\n * console.log([...queue]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(queue.length); // 5;\n * @example\n * // Queue shift and peek operations\n * const queue = new Queue<number>([10, 20, 30, 40]);\n *\n * // Peek at the front element without removing it\n * console.log(queue.first); // 10;\n *\n * // Remove and get the first element (FIFO)\n * const first = queue.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements and length decreased\n * console.log([...queue]); // [20, 30, 40];\n * console.log(queue.length); // 3;\n * @example\n * // Queue for...of iteration and isEmpty check\n * const queue = new Queue<string>(['A', 'B', 'C', 'D']);\n *\n * const elements: string[] = [];\n * for (const item of queue) {\n * elements.push(item);\n * }\n *\n * // Verify all elements are iterated in order\n * console.log(elements); // ['A', 'B', 'C', 'D'];\n *\n * // Process all elements\n * while (queue.length > 0) {\n * queue.shift();\n * }\n *\n * console.log(queue.length); // 0;\n * @example\n * // Queue as message broker for event processing\n * interface Message {\n * id: string;\n * type: 'email' | 'sms' | 'push';\n * recipient: string;\n * content: string;\n * timestamp: Date;\n * }\n *\n * // Create a message queue for real-time event processing\n * const messageQueue = new Queue<Message>([\n * {\n * id: 'msg-001',\n * type: 'email',\n * recipient: 'user@example.com',\n * content: 'Welcome!',\n * timestamp: new Date()\n * },\n * {\n * id: 'msg-002',\n * type: 'sms',\n * recipient: '+1234567890',\n * content: 'OTP: 123456',\n * timestamp: new Date()\n * },\n * {\n * id: 'msg-003',\n * type: 'push',\n * recipient: 'device-token-xyz',\n * content: 'New notification',\n * timestamp: new Date()\n * },\n * {\n * id: 'msg-004',\n * type: 'email',\n * recipient: 'admin@example.com',\n * content: 'Daily report',\n * timestamp: new Date()\n * }\n * ]);\n *\n * // Process messages in FIFO order (first message first)\n * const processedMessages: string[] = [];\n * while (messageQueue.length > 0) {\n * const message = messageQueue.shift();\n * if (message) {\n * processedMessages.push(`${message.type}:${message.recipient}`);\n * }\n * }\n *\n * // Verify messages were processed in order\n * console.log(processedMessages); // [\n * // 'email:user@example.com',\n * // 'sms:+1234567890',\n * // 'push:device-token-xyz',\n * // 'email:admin@example.com'\n * // ];\n *\n * // Queue should be empty after processing all messages\n * console.log(messageQueue.length); // 0;\n */\nexport class Queue<E = any, R = any> extends LinearBase<E, R> {\n /**\n * Create a Queue and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn, maxLen, and autoCompactRatio.\n * @returns New Queue instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: QueueOptions<E, R>) {\n super(options);\n if (options) {\n const { autoCompactRatio = 0.5 } = options;\n this._autoCompactRatio = autoCompactRatio;\n }\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the underlying array buffer.\n * @remarks Time O(1), Space O(1)\n * @returns Backing array of elements.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n protected _offset = 0;\n\n /**\n * Get the current start offset into the array.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based offset.\n */\n\n get offset(): number {\n return this._offset;\n }\n\n protected _autoCompactRatio = 0.5;\n\n /**\n * Get the compaction threshold (offset/size).\n * @remarks Time O(1), Space O(1)\n * @returns Auto-compaction ratio in (0,1].\n */\n\n get autoCompactRatio(): number {\n return this._autoCompactRatio;\n }\n\n /**\n * Set the compaction threshold.\n * @remarks Time O(1), Space O(1)\n * @param value - New ratio; compacts when offset/size exceeds this value.\n * @returns void\n */\n\n set autoCompactRatio(value: number) {\n this._autoCompactRatio = value;\n }\n\n /**\n * Get the number of elements currently in the queue.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this.elements.length - this._offset;\n }\n\n /**\n * Get the first element (front) without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Front element or undefined.\n */\n\n get first(): E | undefined {\n return this.length > 0 ? this.elements[this._offset] : undefined;\n }\n\n /**\n * Get the last element (back) without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Back element or undefined.\n */\n\n get last(): E | undefined {\n return this.length > 0 ? this.elements[this.elements.length - 1] : undefined;\n }\n\n /**\n * Create a queue from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @param elements - Array of elements to enqueue in order.\n * @returns A new queue populated from the array.\n */\n\n static fromArray<E>(elements: E[]): Queue<E> {\n return new Queue(elements);\n }\n\n /**\n * Check whether the queue is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n /**\n * Enqueue one element at the back.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to enqueue.\n * @returns True on success.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Enqueue many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Dequeue one element from the front (amortized via offset).\n * @remarks Time O(1) amortized, Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (this.length === 0) return undefined;\n const first = this.first;\n this._offset += 1;\n if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();\n return first;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (strict equality via Object.is).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n for (let i = this._offset; i < this.elements.length; i++) {\n if (Object.is(this.elements[i], element)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the element at a given logical index.\n * @remarks Time O(1), Space O(1)\n * @param index - Zero-based index from the front.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this.length) return undefined;\n return this._elements[this._offset + index];\n }\n\n /**\n * Delete the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the front.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this.length) return undefined;\n const gi = this._offset + index;\n const [deleted] = this.elements.splice(gi, 1);\n return deleted;\n }\n\n /**\n * Insert a new element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the front.\n * @param newElement - Element to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElement: E): boolean {\n if (index < 0 || index > this.length) return false;\n this._elements.splice(this._offset + index, 0, newElement);\n return true;\n }\n\n /**\n * Replace the element at a given index.\n * @remarks Time O(1), Space O(1)\n * @param index - Zero-based index from the front.\n * @param newElement - New element to set.\n * @returns True if updated.\n */\n\n setAt(index: number, newElement: E): boolean {\n if (index < 0 || index >= this.length) return false;\n this._elements[this._offset + index] = newElement;\n return true;\n }\n\n /**\n * Reverse the queue in-place by compacting then reversing.\n * @remarks Time O(N), Space O(N)\n * @returns This queue.\n */\n\n reverse(): this {\n this._elements = this.elements.slice(this._offset).reverse();\n this._offset = 0;\n return this;\n }\n\n /**\n * Remove all elements and reset offset.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n this._offset = 0;\n }\n\n /**\n * Compact storage by discarding consumed head elements.\n * @remarks Time O(N), Space O(N)\n * @returns True when compaction performed.\n */\n\n compact(): boolean {\n this._elements = this.elements.slice(this._offset);\n this._offset = 0;\n return true;\n }\n\n /**\n * Remove and/or insert elements at a position (array-like).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default 0).\n * @param [items] - Elements to insert after `start`.\n * @returns A new queue containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));\n\n const gi = this._offset + start;\n const removedArray = this._elements.splice(gi, deleteCount, ...items);\n\n if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();\n\n const removed = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n removed._setAutoCompactRatio(this._autoCompactRatio);\n removed.pushMany(removedArray);\n\n return removed as unknown as this;\n }\n\n /**\n * Deep clone this queue and its parameters.\n * @remarks Time O(N), Space O(N)\n * @returns A new queue with the same content and options.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setAutoCompactRatio(this._autoCompactRatio);\n for (let i = this._offset; i < this.elements.length; i++) out.push(this.elements[i]);\n return out;\n }\n\n /**\n * Filter elements into a new queue of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (element, index, queue) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new queue with kept elements.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setAutoCompactRatio(this._autoCompactRatio);\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map each element to a new element in a possibly different-typed queue.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, queue) → newElement.\n * @param [options] - Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Queue with mapped elements.\n */\n\n map<EM, RM>(callback: ElementCallback<E, R, EM>, options?: QueueOptions<EM, RM>, thisArg?: unknown): Queue<EM, RM> {\n const out = new (this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: QueueOptions<EM, RM>\n ) => Queue<EM, RM>)([], {\n toElementFn: options?.toElementFn,\n maxLen: options?.maxLen ?? this._maxLen,\n autoCompactRatio: options?.autoCompactRatio ?? this._autoCompactRatio\n });\n let index = 0;\n for (const v of this)\n out.push(thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * Map each element to a new value of the same type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (element, index, queue) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new queue with mapped elements (same element type).\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R>,\n options?: QueueOptions<E, R>\n ) => Queue<E, R>;\n const out = new Ctor([], {\n toElementFn: this.toElementFn,\n maxLen: this._maxLen,\n autoCompactRatio: this._autoCompactRatio\n });\n out._setAutoCompactRatio?.(this._autoCompactRatio);\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out as this;\n }\n\n /**\n * (Protected) Set the internal auto-compaction ratio.\n * @remarks Time O(1), Space O(1)\n * @param value - New ratio to assign.\n * @returns void\n */\n\n protected _setAutoCompactRatio(value: number): void {\n this._autoCompactRatio = value;\n }\n\n /**\n * (Protected) Iterate elements from front to back.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of E.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = this._offset; i < this.elements.length; i++) yield this.elements[i];\n }\n\n /**\n * (Protected) Iterate elements from back to front.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of E.\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n for (let i = this.length - 1; i >= 0; i--) {\n const cur = this.at(i);\n if (cur !== undefined) yield cur;\n }\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind queue instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: QueueOptions<E, R>) => this;\n return new Ctor([], options as QueueOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind queue and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new queue.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Queue instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: QueueOptions<EM, RM>\n ): Queue<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: QueueOptions<EM, RM>\n ) => Queue<EM, RM>;\n return new Ctor(elements, options);\n }\n}\n\n/**\n * Queue implemented over a singly linked list; preserves head/tail operations with linear scans for queries.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * @example examples will be generated by unit test\n */\nexport class LinkedListQueue<E = any, R = any> extends SinglyLinkedList<E, R> {\n /**\n * Deep clone this linked-list-based queue.\n * @remarks Time O(N), Space O(N)\n * @returns A new queue with the same sequence of elements.\n */\n\n override clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n for (const v of this) out.push(v);\n return out;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n DequeOptions,\n ElementCallback,\n IterableElementBaseOptions,\n IterableWithSizeOrLength,\n LinearBaseOptions\n} from '../../types';\nimport { calcMinUnitsRequired, rangeCheck } from '../../utils';\nimport { LinearBase } from '../base/linear-base';\n\n/**\n * Deque implemented with circular buckets allowing O(1) amortized push/pop at both ends.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).\n * 2. Efficient Random Access: Being based on an array, it offers fast random access capability, allowing constant time access to any element.\n * 3. Continuous Memory Allocation: Since it is based on an array, all elements are stored contiguously in memory, which can bring cache friendliness and efficient memory access.\n * 4. Efficiency: Adding and removing elements at both ends of a deque is usually very fast. However, when the dynamic array needs to expand, it may involve copying the entire array to a larger one, and this operation has a time complexity of O(n).\n * 5. Performance jitter: Deque may experience performance jitter, but DoublyLinkedList will not\n * @example\n * // basic Deque creation and push/pop operations\n * // Create a simple Deque with initial values\n * const deque = new Deque([1, 2, 3, 4, 5]);\n *\n * // Verify the deque maintains insertion order\n * console.log([...deque]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(deque.length); // 5;\n *\n * // Push to the end\n * deque.push(6);\n * console.log(deque.length); // 6;\n *\n * // Pop from the end\n * const last = deque.pop();\n * console.log(last); // 6;\n * @example\n * // Deque shift and unshift operations\n * const deque = new Deque<number>([20, 30, 40]);\n *\n * // Unshift adds to the front\n * deque.unshift(10);\n * console.log([...deque]); // [10, 20, 30, 40];\n *\n * // Shift removes from the front (O(1) complexity!)\n * const first = deque.shift();\n * console.log(first); // 10;\n *\n * // Verify remaining elements\n * console.log([...deque]); // [20, 30, 40];\n * console.log(deque.length); // 3;\n * @example\n * // Deque peek at both ends\n * const deque = new Deque<number>([10, 20, 30, 40, 50]);\n *\n * // Get first element without removing\n * const first = deque.at(0);\n * console.log(first); // 10;\n *\n * // Get last element without removing\n * const last = deque.at(deque.length - 1);\n * console.log(last); // 50;\n *\n * // Length unchanged\n * console.log(deque.length); // 5;\n * @example\n * // Deque for...of iteration and reverse\n * const deque = new Deque<string>(['A', 'B', 'C', 'D']);\n *\n * // Iterate forward\n * const forward: string[] = [];\n * for (const item of deque) {\n * forward.push(item);\n * }\n * console.log(forward); // ['A', 'B', 'C', 'D'];\n *\n * // Reverse the deque\n * deque.reverse();\n * const backward: string[] = [];\n * for (const item of deque) {\n * backward.push(item);\n * }\n * console.log(backward); // ['D', 'C', 'B', 'A'];\n * @example\n * // Deque as sliding window for stream processing\n * interface DataPoint {\n * timestamp: number;\n * value: number;\n * sensor: string;\n * }\n *\n * // Create a deque-based sliding window for real-time data aggregation\n * const windowSize = 3;\n * const dataWindow = new Deque<DataPoint>();\n *\n * // Simulate incoming sensor data stream\n * const incomingData: DataPoint[] = [\n * { timestamp: 1000, value: 25.5, sensor: 'temp-01' },\n * { timestamp: 1100, value: 26.2, sensor: 'temp-01' },\n * { timestamp: 1200, value: 25.8, sensor: 'temp-01' },\n * { timestamp: 1300, value: 27.1, sensor: 'temp-01' },\n * { timestamp: 1400, value: 26.9, sensor: 'temp-01' }\n * ];\n *\n * const windowResults: Array<{ avgValue: number; windowSize: number }> = [];\n *\n * for (const dataPoint of incomingData) {\n * // Add new data to the end\n * dataWindow.push(dataPoint);\n *\n * // Remove oldest data when window exceeds size (O(1) from front)\n * if (dataWindow.length > windowSize) {\n * dataWindow.shift();\n * }\n *\n * // Calculate average of current window\n * let sum = 0;\n * for (const point of dataWindow) {\n * sum += point.value;\n * }\n * const avg = sum / dataWindow.length;\n *\n * windowResults.push({\n * avgValue: Math.round(avg * 10) / 10,\n * windowSize: dataWindow.length\n * });\n * }\n *\n * // Verify sliding window behavior\n * console.log(windowResults.length); // 5;\n * console.log(windowResults[0].windowSize); // 1; // First window has 1 element\n * console.log(windowResults[2].windowSize); // 3; // Windows are at max size from 3rd onwards\n * console.log(windowResults[4].windowSize); // 3; // Last window still has 3 elements\n * console.log(dataWindow.length); // 3;\n */\nexport class Deque<E = any, R = any> extends LinearBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a Deque and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable (or iterable-like) of elements/records to insert.\n * @param [options] - Options such as bucketSize, toElementFn, and maxLen.\n * @returns New Deque instance.\n */\n\n constructor(elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = [], options?: DequeOptions<E, R>) {\n super(options);\n\n if (options) {\n const { bucketSize } = options;\n if (typeof bucketSize === 'number') this._bucketSize = bucketSize;\n }\n\n let _size: number;\n if ('length' in elements) {\n _size = typeof elements.length === 'function' ? elements.length() : elements.length;\n } else {\n _size = typeof elements.size === 'function' ? elements.size() : elements.size;\n }\n\n this._bucketCount = calcMinUnitsRequired(_size, this._bucketSize) || 1;\n for (let i = 0; i < this._bucketCount; ++i) {\n this._buckets.push(new Array(this._bucketSize));\n }\n const needBucketNum = calcMinUnitsRequired(_size, this._bucketSize);\n this._bucketFirst = this._bucketLast = (this._bucketCount >> 1) - (needBucketNum >> 1);\n this._firstInBucket = this._lastInBucket = (this._bucketSize - (_size % this._bucketSize)) >> 1;\n this.pushMany(elements);\n }\n\n protected _bucketSize: number = 1 << 12;\n\n /**\n * Get the current bucket size.\n * @remarks Time O(1), Space O(1)\n * @returns Bucket capacity per bucket.\n */\n\n get bucketSize() {\n return this._bucketSize;\n }\n\n protected _bucketFirst = 0;\n\n /**\n * Get the index of the first bucket in use.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based bucket index.\n */\n\n get bucketFirst(): number {\n return this._bucketFirst;\n }\n\n protected _firstInBucket = 0;\n\n /**\n * Get the index inside the first bucket.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based index within the first bucket.\n */\n\n get firstInBucket(): number {\n return this._firstInBucket;\n }\n\n protected _bucketLast = 0;\n\n /**\n * Get the index of the last bucket in use.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based bucket index.\n */\n\n get bucketLast(): number {\n return this._bucketLast;\n }\n\n protected _lastInBucket = 0;\n\n /**\n * Get the index inside the last bucket.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based index within the last bucket.\n */\n\n get lastInBucket(): number {\n return this._lastInBucket;\n }\n\n protected _bucketCount = 0;\n\n /**\n * Get the number of buckets allocated.\n * @remarks Time O(1), Space O(1)\n * @returns Bucket count.\n */\n\n get bucketCount(): number {\n return this._bucketCount;\n }\n\n protected _buckets: E[][] = [];\n\n /**\n * Get the internal buckets array.\n * @remarks Time O(1), Space O(1)\n * @returns Array of buckets storing values.\n */\n\n get buckets() {\n return this._buckets;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements in the deque.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length() {\n return this._length;\n }\n\n /**\n * Get the first element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n if (this._length === 0) return;\n return this._buckets[this._bucketFirst][this._firstInBucket];\n }\n\n /**\n * Get the last element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n if (this._length === 0) return;\n return this._buckets[this._bucketLast][this._lastInBucket];\n }\n\n /**\n * Create a Deque from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - Constructor (subclass) to instantiate.\n * @param data - Array of elements to insert in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Deque populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (\n elements?: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>,\n options?: DequeOptions<E, R>\n ) => any,\n data: E[],\n options?: DequeOptions<E, R>\n ) {\n return new this(data, options);\n }\n\n /**\n * Append one element at the back.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to append.\n * @returns True when appended.\n */\n\n push(element: E): boolean {\n if (this._length) {\n if (this._lastInBucket < this._bucketSize - 1) {\n this._lastInBucket += 1;\n } else if (this._bucketLast < this._bucketCount - 1) {\n this._bucketLast += 1;\n this._lastInBucket = 0;\n } else {\n this._bucketLast = 0;\n this._lastInBucket = 0;\n }\n if (this._bucketLast === this._bucketFirst && this._lastInBucket === this._firstInBucket) this._reallocate();\n }\n this._length += 1;\n this._buckets[this._bucketLast][this._lastInBucket] = element;\n if (this._maxLen > 0 && this._length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the last element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (this._length === 0) return;\n const element = this._buckets[this._bucketLast][this._lastInBucket];\n if (this._length !== 1) {\n if (this._lastInBucket > 0) {\n this._lastInBucket -= 1;\n } else if (this._bucketLast > 0) {\n this._bucketLast -= 1;\n this._lastInBucket = this._bucketSize - 1;\n } else {\n this._bucketLast = this._bucketCount - 1;\n this._lastInBucket = this._bucketSize - 1;\n }\n }\n this._length -= 1;\n return element;\n }\n\n /**\n * Remove and return the first element.\n * @remarks Time O(1) amortized, Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (this._length === 0) return;\n const element = this._buckets[this._bucketFirst][this._firstInBucket];\n if (this._length !== 1) {\n if (this._firstInBucket < this._bucketSize - 1) {\n this._firstInBucket += 1;\n } else if (this._bucketFirst < this._bucketCount - 1) {\n this._bucketFirst += 1;\n this._firstInBucket = 0;\n } else {\n this._bucketFirst = 0;\n this._firstInBucket = 0;\n }\n }\n this._length -= 1;\n return element;\n }\n\n /**\n * Prepend one element at the front.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to prepend.\n * @returns True when prepended.\n */\n\n unshift(element: E): boolean {\n if (this._length) {\n if (this._firstInBucket > 0) {\n this._firstInBucket -= 1;\n } else if (this._bucketFirst > 0) {\n this._bucketFirst -= 1;\n this._firstInBucket = this._bucketSize - 1;\n } else {\n this._bucketFirst = this._bucketCount - 1;\n this._firstInBucket = this._bucketSize - 1;\n }\n if (this._bucketFirst === this._bucketLast && this._firstInBucket === this._lastInBucket) this._reallocate();\n }\n this._length += 1;\n this._buckets[this._bucketFirst][this._firstInBucket] = element;\n if (this._maxLen > 0 && this._length > this._maxLen) this.pop();\n return true;\n }\n\n /**\n * Append a sequence of elements.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable (or iterable-like) of elements/records.\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>) {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n ans.push(this.push(this.toElementFn(el as R)));\n } else {\n ans.push(this.push(el as E));\n }\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements.\n * @remarks Time O(N), Space O(1)\n * @param [elements] - Iterable (or iterable-like) of elements/records.\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = []) {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n ans.push(this.unshift(this.toElementFn(el as R)));\n } else {\n ans.push(this.unshift(el as E));\n }\n }\n return ans;\n }\n\n /**\n * Check whether the deque is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this._length === 0;\n }\n\n /**\n * Remove all elements and reset structure.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._buckets = [new Array(this._bucketSize)];\n this._bucketCount = 1;\n this._bucketFirst = this._bucketLast = this._length = 0;\n this._firstInBucket = this._lastInBucket = this._bucketSize >> 1;\n }\n\n /**\n * Get the element at a given position.\n * @remarks Time O(1), Space O(1)\n * @param pos - Zero-based position from the front.\n * @returns Element or undefined.\n */\n\n at(pos: number): E | undefined {\n if (pos < 0 || pos >= this._length) return undefined;\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n return this._buckets[bucketIndex][indexInBucket];\n }\n\n /**\n * Replace the element at a given position.\n * @remarks Time O(1), Space O(1)\n * @param pos - Zero-based position from the front.\n * @param element - New element value.\n * @returns True if updated.\n */\n\n setAt(pos: number, element: E): boolean {\n rangeCheck(pos, 0, this._length - 1);\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n this._buckets[bucketIndex][indexInBucket] = element;\n return true;\n }\n\n /**\n * Insert repeated copies of an element at a position.\n * @remarks Time O(N), Space O(1)\n * @param pos - Zero-based position from the front.\n * @param element - Element to insert.\n * @param [num] - Number of times to insert (default 1).\n * @returns True if inserted.\n */\n\n addAt(pos: number, element: E, num = 1): boolean {\n const length = this._length;\n rangeCheck(pos, 0, length);\n if (pos === 0) {\n while (num--) this.unshift(element);\n } else if (pos === this._length) {\n while (num--) this.push(element);\n } else {\n const arr: E[] = [];\n for (let i = pos; i < this._length; ++i) {\n const v = this.at(i);\n if (v !== undefined) arr.push(v);\n }\n this.cut(pos - 1, true);\n for (let i = 0; i < num; ++i) this.push(element);\n for (let i = 0; i < arr.length; ++i) this.push(arr[i]);\n }\n return true;\n }\n\n /**\n * Cut the deque to keep items up to index; optionally mutate in-place.\n * @remarks Time O(N), Space O(1)\n * @param pos - Last index to keep.\n * @param [isCutSelf] - When true, mutate this deque; otherwise return a new deque.\n * @returns This deque if in-place; otherwise a new deque of the prefix.\n */\n\n cut(pos: number, isCutSelf = false): Deque<E> {\n if (isCutSelf) {\n if (pos < 0) {\n this.clear();\n return this;\n }\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n this._bucketLast = bucketIndex;\n this._lastInBucket = indexInBucket;\n this._length = pos + 1;\n return this;\n } else {\n const newDeque = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n newDeque._setBucketSize(this._bucketSize);\n for (let i = 0; i <= pos; i++) {\n const v = this.at(i);\n if (v !== undefined) newDeque.push(v);\n }\n\n return newDeque;\n }\n }\n\n /**\n * Remove and/or insert elements at a position (array-like behavior).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default: length - start).\n * @param [items] - Elements to insert after `start`.\n * @returns A new deque containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount: number = this._length - start, ...items: E[]): this {\n rangeCheck(start, 0, this._length);\n if (deleteCount < 0) deleteCount = 0;\n if (start + deleteCount > this._length) deleteCount = this._length - start;\n\n const removed = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n removed._setBucketSize(this._bucketSize);\n for (let i = 0; i < deleteCount; i++) {\n const v = this.at(start + i);\n if (v !== undefined) removed.push(v);\n }\n\n const tail: E[] = [];\n for (let i = start + deleteCount; i < this._length; i++) {\n const v = this.at(i);\n if (v !== undefined) tail.push(v);\n }\n\n this.cut(start - 1, true);\n\n for (const it of items) this.push(it);\n\n for (const v of tail) this.push(v);\n\n return removed as unknown as this;\n }\n\n /**\n * Cut the deque to keep items from index onward; optionally mutate in-place.\n * @remarks Time O(N), Space O(1)\n * @param pos - First index to keep.\n * @param [isCutSelf] - When true, mutate this deque; otherwise return a new deque.\n * @returns This deque if in-place; otherwise a new deque of the suffix.\n */\n\n cutRest(pos: number, isCutSelf = false): Deque<E> {\n if (isCutSelf) {\n if (pos < 0) {\n return this;\n }\n const { bucketIndex, indexInBucket } = this._getBucketAndPosition(pos);\n this._bucketFirst = bucketIndex;\n this._firstInBucket = indexInBucket;\n this._length = this._length - pos;\n return this;\n } else {\n const newDeque = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n newDeque._setBucketSize(this._bucketSize);\n if (pos < 0) pos = 0;\n for (let i = pos; i < this._length; i++) {\n const v = this.at(i);\n if (v !== undefined) newDeque.push(v);\n }\n return newDeque;\n }\n }\n\n /**\n * Delete the element at a given position.\n * @remarks Time O(N), Space O(1)\n * @param pos - Zero-based position from the front.\n * @returns Removed element or undefined.\n */\n\n deleteAt(pos: number): E | undefined {\n rangeCheck(pos, 0, this._length - 1);\n\n let deleted: E | undefined;\n if (pos === 0) {\n return this.shift();\n } else if (pos === this._length - 1) {\n deleted = this.last;\n this.pop();\n return deleted;\n } else {\n const length = this._length - 1;\n const { bucketIndex: targetBucket, indexInBucket: targetPointer } = this._getBucketAndPosition(pos);\n deleted = this._buckets[targetBucket][targetPointer];\n\n for (let i = pos; i < length; i++) {\n const { bucketIndex: curBucket, indexInBucket: curPointer } = this._getBucketAndPosition(i);\n const { bucketIndex: nextBucket, indexInBucket: nextPointer } = this._getBucketAndPosition(i + 1);\n this._buckets[curBucket][curPointer] = this._buckets[nextBucket][nextPointer];\n }\n\n this.pop();\n return deleted;\n }\n }\n\n /**\n * Delete the first occurrence of a value.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const size = this._length;\n if (size === 0) return false;\n let i = 0;\n let index = 0;\n while (i < size) {\n const oldElement = this.at(i);\n if (!this._equals(oldElement as E, element)) {\n this.setAt(index, oldElement!);\n index += 1;\n }\n i += 1;\n }\n this.cut(index - 1, true);\n return true;\n }\n\n /**\n * Delete the first element matching a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, deque) → boolean.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, deque: this) => boolean): boolean {\n for (let i = 0; i < this._length; i++) {\n const v = this.at(i);\n if (predicate(v as E, i, this)) {\n this.deleteAt(i);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Set the equality comparator used by delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This deque.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Reverse the deque by reversing buckets and pointers.\n * @remarks Time O(N), Space O(N)\n * @returns This deque.\n */\n\n reverse(): this {\n this._buckets.reverse().forEach(function (bucket) {\n bucket.reverse();\n });\n const { _bucketFirst, _bucketLast, _firstInBucket, _lastInBucket } = this;\n this._bucketFirst = this._bucketCount - _bucketLast - 1;\n this._bucketLast = this._bucketCount - _bucketFirst - 1;\n this._firstInBucket = this._bucketSize - _lastInBucket - 1;\n this._lastInBucket = this._bucketSize - _firstInBucket - 1;\n return this;\n }\n\n /**\n * Deduplicate consecutive equal elements in-place.\n * @remarks Time O(N), Space O(1)\n * @returns This deque.\n */\n\n unique(): this {\n if (this._length <= 1) {\n return this;\n }\n let index = 1;\n let prev = this.at(0);\n for (let i = 1; i < this._length; ++i) {\n const cur = this.at(i);\n if (!this._equals(cur as E, prev as E)) {\n prev = cur;\n this.setAt(index++, cur as E);\n }\n }\n this.cut(index - 1, true);\n return this;\n }\n\n /**\n * Trim unused buckets to fit exactly the active range.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n shrinkToFit(): void {\n if (this._length === 0) return;\n const newBuckets = [] as E[][];\n if (this._bucketFirst === this._bucketLast) return;\n else if (this._bucketFirst < this._bucketLast) {\n for (let i = this._bucketFirst; i <= this._bucketLast; ++i) {\n newBuckets.push(this._buckets[i]);\n }\n } else {\n for (let i = this._bucketFirst; i < this._bucketCount; ++i) {\n newBuckets.push(this._buckets[i]);\n }\n for (let i = 0; i <= this._bucketLast; ++i) {\n newBuckets.push(this._buckets[i]);\n }\n }\n this._bucketFirst = 0;\n this._bucketLast = newBuckets.length - 1;\n this._buckets = newBuckets;\n }\n\n /**\n * Deep clone this deque, preserving options.\n * @remarks Time O(N), Space O(N)\n * @returns A new deque with the same content and options.\n */\n\n clone(): this {\n return this._createLike<E, R>(this, {\n bucketSize: this.bucketSize,\n toElementFn: this.toElementFn,\n maxLen: this._maxLen\n }) as this;\n }\n\n /**\n * Filter elements into a new deque of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, deque) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new deque with kept elements.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setBucketSize(this._bucketSize);\n let index = 0;\n for (const el of this) {\n if (predicate.call(thisArg, el, index, this)) out.push(el);\n index++;\n }\n return out;\n }\n\n /**\n * Map elements into a new deque of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, deque) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new deque with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n out._setBucketSize(this._bucketSize);\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map elements into a new deque (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, deque) → newElement.\n * @param [options] - Options for the output deque (e.g., bucketSize, toElementFn, maxLen).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Deque with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: any\n ): Deque<EM, RM> {\n const out = this._createLike<EM, RM>([], {\n ...(options ?? {}),\n bucketSize: this._bucketSize,\n maxLen: this._maxLen\n }) as Deque<EM, RM>;\n let index = 0;\n for (const el of this) {\n const mv = thisArg === undefined ? callback(el, index, this) : callback.call(thisArg, el, index, this);\n out.push(mv);\n index++;\n }\n return out;\n }\n\n /**\n * (Protected) Set the internal bucket size.\n * @remarks Time O(1), Space O(1)\n * @param size - Bucket capacity to assign.\n * @returns void\n */\n\n protected _setBucketSize(size: number): void {\n this._bucketSize = size;\n }\n\n /**\n * (Protected) Iterate elements from front to back.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this._length; ++i) {\n const v = this.at(i);\n if (v !== undefined) yield v;\n }\n }\n\n /**\n * (Protected) Reallocate buckets to make room near the ends.\n * @remarks Time O(N), Space O(N)\n * @param [needBucketNum] - How many extra buckets to add; defaults to half of current.\n * @returns void\n */\n\n protected _reallocate(needBucketNum?: number) {\n const newBuckets = [] as E[][];\n const addBucketNum = needBucketNum || this._bucketCount >> 1 || 1;\n for (let i = 0; i < addBucketNum; ++i) {\n newBuckets[i] = new Array(this._bucketSize);\n }\n for (let i = this._bucketFirst; i < this._bucketCount; ++i) {\n newBuckets[newBuckets.length] = this._buckets[i];\n }\n for (let i = 0; i < this._bucketLast; ++i) {\n newBuckets[newBuckets.length] = this._buckets[i];\n }\n newBuckets[newBuckets.length] = [...this._buckets[this._bucketLast]];\n this._bucketFirst = addBucketNum;\n this._bucketLast = newBuckets.length - 1;\n for (let i = 0; i < addBucketNum; ++i) {\n newBuckets[newBuckets.length] = new Array(this._bucketSize);\n }\n this._buckets = newBuckets;\n this._bucketCount = newBuckets.length;\n }\n\n /**\n * (Protected) Translate a logical position to bucket/offset.\n * @remarks Time O(1), Space O(1)\n * @param pos - Zero-based position.\n * @returns An object containing bucketIndex and indexInBucket.\n */\n\n protected _getBucketAndPosition(pos: number) {\n let bucketIndex: number;\n let indexInBucket: number;\n\n const overallIndex = this._firstInBucket + pos;\n bucketIndex = this._bucketFirst + Math.floor(overallIndex / this._bucketSize);\n\n if (bucketIndex >= this._bucketCount) {\n bucketIndex -= this._bucketCount;\n }\n\n indexInBucket = ((overallIndex + 1) % this._bucketSize) - 1;\n if (indexInBucket < 0) {\n indexInBucket = this._bucketSize - 1;\n }\n\n return { bucketIndex, indexInBucket };\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind deque instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>,\n options?: DequeOptions<E, R>\n ) => this;\n return new Ctor([], options as DequeOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind deque seeded by elements.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new deque.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Deque instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: IterableWithSizeOrLength<T> | IterableWithSizeOrLength<RR> = [],\n options?: DequeOptions<T, RR>\n ): any {\n const Ctor = this.constructor as new (\n elements?: IterableWithSizeOrLength<T> | IterableWithSizeOrLength<RR>,\n options?: DequeOptions<T, RR>\n ) => any;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from back to front.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n for (let i = this._length - 1; i > -1; i--) {\n const v = this.at(i);\n if (v !== undefined) yield v;\n }\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: Each node in a heap follows a specific order property, which varies depending on the type of heap:\n * Max Heap: The value of each parent node is greater than or equal to the value of its children.\n * Min Heap: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n * // basic Heap creation and add operation\n * // Create a min heap (default)\n * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);\n *\n * // Verify size\n * console.log(minHeap.size); // 6;\n *\n * // Add new element\n * minHeap.add(4);\n * console.log(minHeap.size); // 7;\n *\n * // Min heap property: smallest element at root\n * const min = minHeap.peek();\n * console.log(min); // 1;\n * @example\n * // Heap with custom comparator (MaxHeap behavior)\n * interface Task {\n * id: number;\n * priority: number;\n * name: string;\n * }\n *\n * // Custom comparator for max heap behavior (higher priority first)\n * const tasks: Task[] = [\n * { id: 1, priority: 5, name: 'Email' },\n * { id: 2, priority: 3, name: 'Chat' },\n * { id: 3, priority: 8, name: 'Alert' }\n * ];\n *\n * const maxHeap = new Heap(tasks, {\n * comparator: (a: Task, b: Task) => b.priority - a.priority\n * });\n *\n * console.log(maxHeap.size); // 3;\n *\n * // Peek returns highest priority task\n * const topTask = maxHeap.peek();\n * console.log(topTask?.priority); // 8;\n * console.log(topTask?.name); // 'Alert';\n * @example\n * // Heap for event processing with priority\n * interface Event {\n * id: number;\n * type: 'critical' | 'warning' | 'info';\n * timestamp: number;\n * message: string;\n * }\n *\n * // Custom priority: critical > warning > info\n * const priorityMap = { critical: 3, warning: 2, info: 1 };\n *\n * const eventHeap = new Heap<Event>([], {\n * comparator: (a: Event, b: Event) => {\n * const priorityA = priorityMap[a.type];\n * const priorityB = priorityMap[b.type];\n * return priorityB - priorityA; // Higher priority first\n * }\n * });\n *\n * // Add events in random order\n * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });\n * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });\n * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });\n * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });\n * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });\n *\n * console.log(eventHeap.size); // 5;\n *\n * // Process events by priority (critical first)\n * const processedOrder: Event[] = [];\n * while (eventHeap.size > 0) {\n * const event = eventHeap.poll();\n * if (event) {\n * processedOrder.push(event);\n * }\n * }\n *\n * // Verify critical events came first\n * console.log(processedOrder[0].type); // 'critical';\n * console.log(processedOrder[1].type); // 'critical';\n * console.log(processedOrder[2].type); // 'warning';\n * console.log(processedOrder[3].type); // 'info';\n * console.log(processedOrder[4].type); // 'info';\n *\n * // Verify O(log n) operations\n * const newHeap = new Heap<number>([5, 3, 7, 1]);\n *\n * // Add - O(log n)\n * newHeap.add(2);\n * console.log(newHeap.size); // 5;\n *\n * // Poll - O(log n)\n * const removed = newHeap.poll();\n * console.log(removed); // 1;\n *\n * // Peek - O(1)\n * const top = newHeap.peek();\n * console.log(top); // 2;\n * @example\n * // Use Heap to solve top k problems\n * function topKElements(arr: number[], k: number): number[] {\n * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap\n * arr.forEach(num => {\n * heap.add(num);\n * if (heap.size > k) heap.poll(); // Keep the heap size at K\n * });\n * return heap.toArray();\n * }\n *\n * const numbers = [10, 30, 20, 5, 15, 25];\n * console.log(topKElements(numbers, 3)); // [15, 10, 5];\n * @example\n * // Use Heap to dynamically maintain the median\n * class MedianFinder {\n * private low: MaxHeap<number>; // Max heap, stores the smaller half\n * private high: MinHeap<number>; // Min heap, stores the larger half\n *\n * constructor() {\n * this.low = new MaxHeap<number>([]);\n * this.high = new MinHeap<number>([]);\n * }\n *\n * addNum(num: number): void {\n * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);\n * else this.high.add(num);\n *\n * // Balance heaps\n * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);\n * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);\n * }\n *\n * findMedian(): number {\n * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;\n * return this.low.peek()!;\n * }\n * }\n *\n * const medianFinder = new MedianFinder();\n * medianFinder.addNum(10);\n * console.log(medianFinder.findMedian()); // 10;\n * medianFinder.addNum(20);\n * console.log(medianFinder.findMedian()); // 15;\n * medianFinder.addNum(30);\n * console.log(medianFinder.findMedian()); // 20;\n * medianFinder.addNum(40);\n * console.log(medianFinder.findMedian()); // 25;\n * medianFinder.addNum(50);\n * console.log(medianFinder.findMedian()); // 30;\n * @example\n * // Use Heap for load balancing\n * function loadBalance(requests: number[], servers: number): number[] {\n * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap\n * const serverLoads = new Array(servers).fill(0);\n *\n * for (let i = 0; i < servers; i++) {\n * serverHeap.add({ id: i, load: 0 });\n * }\n *\n * requests.forEach(req => {\n * const server = serverHeap.poll()!;\n * serverLoads[server.id] += req;\n * server.load += req;\n * serverHeap.add(server); // The server after updating the load is re-entered into the heap\n * });\n *\n * return serverLoads;\n * }\n *\n * const requests = [5, 2, 8, 3, 7];\n * console.log(loadBalance(requests, 3)); // [12, 8, 5];\n * @example\n * // Use Heap to schedule tasks\n * type Task = [string, number];\n *\n * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {\n * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap\n * const allocation = new Map<number, Task[]>();\n *\n * // Initialize the load on each machine\n * for (let i = 0; i < machines; i++) {\n * machineHeap.add({ id: i, load: 0 });\n * allocation.set(i, []);\n * }\n *\n * // Assign tasks\n * tasks.forEach(([task, load]) => {\n * const machine = machineHeap.poll()!;\n * allocation.get(machine.id)!.push([task, load]);\n * machine.load += load;\n * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap\n * });\n *\n * return allocation;\n * }\n *\n * const tasks: Task[] = [\n * ['Task1', 3],\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task4', 5],\n * ['Task5', 4]\n * ];\n * const expectedMap = new Map<number, Task[]>();\n * expectedMap.set(0, [\n * ['Task1', 3],\n * ['Task4', 5]\n * ]);\n * expectedMap.set(1, [\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task5', 4]\n * ]);\n * console.log(scheduleTasks(tasks, 2)); // expectedMap;\n */\nexport class Heap<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is;\n\n /**\n * Create a Heap and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw values if toElementFn is set).\n * @param [options] - Options such as comparator and toElementFn.\n * @returns New Heap instance.\n */\n\n constructor(elements: Iterable<E | R> = [], options?: HeapOptions<E, R>) {\n super(options);\n\n if (options) {\n const { comparator } = options;\n if (comparator) this._comparator = comparator;\n }\n\n this.addMany(elements as Iterable<E | R>);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of the heap.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Heap size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Get the last leaf element.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get leaf(): E | undefined {\n return this.elements[this.size - 1] ?? undefined;\n }\n\n /**\n * Create a heap of the same class from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template R\n * @template S\n * @param [elements] - Iterable of elements or raw records.\n * @param [options] - Heap options including comparator.\n * @returns A new heap instance of this class.\n */\n\n static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(\n this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,\n elements?: Iterable<T | R>,\n options?: HeapOptions<T, R>\n ): S {\n return new this(elements, options);\n }\n\n /**\n * Build a Heap from an iterable in linear time given a comparator.\n * @remarks Time O(N), Space O(N)\n * @template EE\n * @template RR\n * @param elements - Iterable of elements.\n * @param options - Heap options including comparator.\n * @returns A new Heap built from elements.\n */\n\n static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {\n return new Heap<EE, RR>(elements, options);\n }\n\n /**\n * Insert an element.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns True.\n */\n\n add(element: E): boolean {\n this._elements.push(element);\n return this._bubbleUp(this.elements.length - 1);\n }\n\n /**\n * Insert many elements from an iterable.\n * @remarks Time O(N log N), Space O(1)\n * @param elements - Iterable of elements or raw values.\n * @returns Array of per-element success flags.\n */\n\n addMany(elements: Iterable<E | R>): boolean[] {\n const flags: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n const ok = this.add(this.toElementFn(el as R));\n flags.push(ok);\n } else {\n const ok = this.add(el as E);\n flags.push(ok);\n }\n }\n return flags;\n }\n\n /**\n * Remove and return the top element.\n * @remarks Time O(log N), Space O(1)\n * @returns Top element or undefined.\n */\n\n poll(): E | undefined {\n if (this.elements.length === 0) return;\n const value = this.elements[0];\n const last = this.elements.pop()!;\n if (this.elements.length) {\n this.elements[0] = last;\n this._sinkDown(0, this.elements.length >> 1);\n }\n return value;\n }\n\n /**\n * Get the current top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.elements[0];\n }\n\n /**\n * Check whether the heap is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Remove all elements.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Replace the backing array and rebuild the heap.\n * @remarks Time O(N), Space O(N)\n * @param elements - Iterable used to refill the heap.\n * @returns Array of per-node results from fixing steps.\n */\n\n refill(elements: Iterable<E>): boolean[] {\n this._elements = Array.from(elements);\n return this.fix();\n }\n\n /**\n * Check if an equal element exists in the heap.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to search for.\n * @returns True if found.\n */\n\n override has(element: E): boolean {\n for (const el of this.elements) if (this._equals(el, element)) return true;\n return false;\n }\n\n /**\n * Delete one occurrence of an element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to delete.\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n let index = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (this._equals(this.elements[i], element)) {\n index = i;\n break;\n }\n }\n if (index < 0) return false;\n if (index === 0) {\n this.poll();\n } else if (index === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(index, 1, this.elements.pop()!);\n this._bubbleUp(index);\n this._sinkDown(index, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Delete the first element that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (element, index, heap) → boolean.\n * @returns True if an element was removed.\n */\n\n deleteBy(predicate: (element: E, index: number, heap: this) => boolean): boolean {\n let idx = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n idx = i;\n break;\n }\n }\n if (idx < 0) return false;\n if (idx === 0) {\n this.poll();\n } else if (idx === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(idx, 1, this.elements.pop()!);\n this._bubbleUp(idx);\n this._sinkDown(idx, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Set the equality comparator used by has/delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This heap.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Traverse the binary heap as a complete binary tree and collect elements.\n * @remarks Time O(N), Space O(H)\n * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.\n * @returns Array of visited elements.\n */\n\n dfs(order: DFSOrderPattern = 'PRE'): E[] {\n const result: E[] = [];\n const _dfs = (index: number) => {\n const left = 2 * index + 1,\n right = left + 1;\n if (index < this.size) {\n if (order === 'IN') {\n _dfs(left);\n result.push(this.elements[index]);\n _dfs(right);\n } else if (order === 'PRE') {\n result.push(this.elements[index]);\n _dfs(left);\n _dfs(right);\n } else if (order === 'POST') {\n _dfs(left);\n _dfs(right);\n result.push(this.elements[index]);\n }\n }\n };\n _dfs(0);\n return result;\n }\n\n /**\n * Restore heap order bottom-up (heapify in-place).\n * @remarks Time O(N), Space O(1)\n * @returns Array of per-node results from fixing steps.\n */\n\n fix(): boolean[] {\n const results: boolean[] = [];\n for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {\n results.push(this._sinkDown(i, this.elements.length >> 1));\n }\n return results;\n }\n\n /**\n * Return all elements in ascending order by repeatedly polling.\n * @remarks Time O(N log N), Space O(N)\n * @returns Sorted array of elements.\n */\n\n sort(): E[] {\n const visited: E[] = [];\n const cloned = this._createInstance();\n for (const x of this.elements) cloned.add(x);\n while (!cloned.isEmpty()) {\n const top = cloned.poll();\n if (top !== undefined) visited.push(top);\n }\n return visited;\n }\n\n /**\n * Deep clone this heap.\n * @remarks Time O(N), Space O(N)\n * @returns A new heap with the same elements.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this.elements) next.add(x);\n return next;\n }\n\n /**\n * Filter elements into a new heap of the same class.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Predicate (element, index, heap) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with the kept elements.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n if (thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {\n out.add(x);\n } else {\n i++;\n }\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of possibly different element type.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, heap) → newElement.\n * @param options - Options for the output heap, including comparator for EM.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options: HeapOptions<EM, RM> & { comparator: Comparator<EM> },\n thisArg?: unknown\n ): Heap<EM, RM> {\n const { comparator, toElementFn, ...rest } = options ?? {};\n if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');\n const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of the same element type.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Mapping function (element, index, heap) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n protected _DEFAULT_COMPARATOR = (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError('When comparing object types, define a custom comparator in options.');\n }\n if ((a as unknown as number) > (b as unknown as number)) return 1;\n if ((a as unknown as number) < (b as unknown as number)) return -1;\n return 0;\n };\n\n protected _comparator: Comparator<E> = this._DEFAULT_COMPARATOR; /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n\n get comparator() {\n return this._comparator;\n }\n\n protected *_getIterator(): IterableIterator<E> {\n for (const element of this.elements) yield element;\n }\n\n protected _bubbleUp(index: number): boolean {\n const element = this.elements[index];\n while (index > 0) {\n const parent = (index - 1) >> 1;\n const parentItem = this.elements[parent];\n if (this.comparator(parentItem, element) <= 0) break;\n this.elements[index] = parentItem;\n index = parent;\n }\n this.elements[index] = element;\n return true;\n }\n\n protected _sinkDown(index: number, halfLength: number): boolean {\n const element = this.elements[index];\n while (index < halfLength) {\n let left = (index << 1) | 1;\n const right = left + 1;\n let minItem = this.elements[left];\n if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {\n left = right;\n minItem = this.elements[right];\n }\n if (this.comparator(minItem, element) >= 0) break;\n this.elements[index] = minItem;\n index = left;\n }\n this.elements[index] = element;\n return true;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options to override comparator or toElementFn.\n * @returns A like-kind empty heap instance.\n */\n\n protected _createInstance(options?: HeapOptions<E, R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...(options ?? {}) });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind instance seeded by elements.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable of elements or raw values to seed.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind heap instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: HeapOptions<EM, RM>\n ): Heap<EM, RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Heap<EM, RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind heap instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind heap instance.\n */\n\n protected _spawnLike<EM, RM>(options?: HeapOptions<EM, RM>): Heap<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\n/**\n * Node container used by FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class FibonacciHeapNode<E> {\n element: E;\n degree: number;\n left?: FibonacciHeapNode<E>;\n right?: FibonacciHeapNode<E>;\n child?: FibonacciHeapNode<E>;\n parent?: FibonacciHeapNode<E>;\n marked: boolean;\n\n constructor(element: E, degree = 0) {\n this.element = element;\n this.degree = degree;\n this.marked = false;\n }\n}\n\n/**\n * Fibonacci heap (min-heap) optimized for fast merges and amortized operations.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @example examples will be generated by unit test\n */\nexport class FibonacciHeap<E> {\n /**\n * Create a FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @param [comparator] - Comparator to order elements (min-heap by default).\n * @returns New FibonacciHeap instance.\n */\n\n constructor(comparator?: Comparator<E>) {\n this.clear();\n this._comparator = comparator || this._defaultComparator;\n if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');\n }\n\n protected _root?: FibonacciHeapNode<E>;\n\n /**\n * Get the circular root list head.\n * @remarks Time O(1), Space O(1)\n * @returns Root node or undefined.\n */\n\n get root(): FibonacciHeapNode<E> | undefined {\n return this._root;\n }\n\n protected _size = 0;\n get size(): number {\n return this._size;\n }\n\n protected _min?: FibonacciHeapNode<E>;\n\n /**\n * Get the current minimum node.\n * @remarks Time O(1), Space O(1)\n * @returns Min node or undefined.\n */\n\n get min(): FibonacciHeapNode<E> | undefined {\n return this._min;\n }\n\n protected _comparator: Comparator<E>;\n get comparator(): Comparator<E> {\n return this._comparator;\n }\n\n clear(): void {\n this._root = undefined;\n this._min = undefined;\n this._size = 0;\n }\n\n add(element: E): boolean {\n this.push(element);\n return true;\n }\n\n /**\n * Push an element into the root list.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns This heap.\n */\n\n push(element: E): this {\n const node = this.createNode(element);\n node.left = node;\n node.right = node;\n this.mergeWithRoot(node);\n if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;\n this._size++;\n return this;\n }\n\n peek(): E | undefined {\n return this.min ? this.min.element : undefined;\n }\n\n /**\n * Collect nodes from a circular doubly linked list starting at head.\n * @remarks Time O(K), Space O(K)\n * @param [head] - Start node of the circular list.\n * @returns Array of nodes from the list.\n */\n\n consumeLinkedList(head?: FibonacciHeapNode<E>): FibonacciHeapNode<E>[] {\n const elements: FibonacciHeapNode<E>[] = [];\n if (!head) return elements;\n let node: FibonacciHeapNode<E> | undefined = head;\n let started = false;\n while (true) {\n if (node === head && started) break;\n else if (node === head) started = true;\n elements.push(node!);\n node = node!.right;\n }\n return elements;\n }\n\n /**\n * Insert a node into a parent's child list (circular).\n * @remarks Time O(1), Space O(1)\n * @param parent - Parent node.\n * @param node - Child node to insert.\n * @returns void\n */\n\n mergeWithChild(parent: FibonacciHeapNode<E>, node: FibonacciHeapNode<E>): void {\n if (!parent.child) parent.child = node;\n else {\n node.right = parent.child.right;\n node.left = parent.child;\n parent.child.right!.left = node;\n parent.child.right = node;\n }\n }\n\n poll(): E | undefined {\n return this.pop();\n }\n\n /**\n * Remove and return the minimum element, consolidating the root list.\n * @remarks Time O(log N) amortized, Space O(1)\n * @returns Minimum element or undefined.\n */\n\n pop(): E | undefined {\n if (this._size === 0) return undefined;\n const z = this.min!;\n if (z.child) {\n const elements = this.consumeLinkedList(z.child);\n for (const node of elements) {\n this.mergeWithRoot(node);\n node.parent = undefined;\n }\n }\n this.removeFromRoot(z);\n if (z === z.right) {\n this._min = undefined;\n this._root = undefined;\n } else {\n this._min = z.right;\n this._consolidate();\n }\n this._size--;\n return z.element;\n }\n\n /**\n * Meld another heap into this heap.\n * @remarks Time O(1), Space O(1)\n * @param heapToMerge - Another FibonacciHeap to meld into this one.\n * @returns void\n */\n\n merge(heapToMerge: FibonacciHeap<E>): void {\n if (heapToMerge.size === 0) return;\n if (this.root && heapToMerge.root) {\n const thisRoot = this.root,\n otherRoot = heapToMerge.root;\n const thisRootRight = thisRoot.right!,\n otherRootLeft = otherRoot.left!;\n thisRoot.right = otherRoot;\n otherRoot.left = thisRoot;\n thisRootRight.left = otherRootLeft;\n otherRootLeft.right = thisRootRight;\n } else if (!this.root && heapToMerge.root) {\n this._root = heapToMerge.root;\n }\n if (!this.min || (heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0)) {\n this._min = heapToMerge.min;\n }\n this._size += heapToMerge.size;\n heapToMerge.clear();\n }\n\n createNode(element: E): FibonacciHeapNode<E> {\n return new FibonacciHeapNode<E>(element);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n protected _defaultComparator(a: E, b: E): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n protected mergeWithRoot(node: FibonacciHeapNode<E>): void {\n if (!this.root) this._root = node;\n else {\n node.right = this.root.right;\n node.left = this.root;\n this.root.right!.left = node;\n this.root.right = node;\n }\n }\n\n protected removeFromRoot(node: FibonacciHeapNode<E>): void {\n if (this.root === node) this._root = node.right;\n if (node.left) node.left.right = node.right;\n if (node.right) node.right.left = node.left;\n }\n\n protected _link(y: FibonacciHeapNode<E>, x: FibonacciHeapNode<E>): void {\n this.removeFromRoot(y);\n y.left = y;\n y.right = y;\n this.mergeWithChild(x, y);\n x.degree++;\n y.parent = x;\n }\n\n protected _consolidate(): void {\n const A: (FibonacciHeapNode<E> | undefined)[] = new Array(this._size);\n const elements = this.consumeLinkedList(this.root);\n let x: FibonacciHeapNode<E> | undefined,\n y: FibonacciHeapNode<E> | undefined,\n d: number,\n t: FibonacciHeapNode<E> | undefined;\n\n for (const node of elements) {\n x = node;\n d = x.degree;\n while (A[d]) {\n y = A[d] as FibonacciHeapNode<E>;\n if (this.comparator(x.element, y.element) > 0) {\n t = x;\n x = y;\n y = t;\n }\n this._link(y, x);\n A[d] = undefined;\n d++;\n }\n A[d] = x;\n }\n\n for (let i = 0; i < A.length; i++) {\n if (A[i] && (!this.min || this.comparator(A[i]!.element, this.min.element) <= 0)) this._min = A[i]!;\n }\n }\n}\n","/**\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Max-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. Heap Properties: The value of each parent node is greater than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MaxHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a max-heap. For objects, supply a custom comparator.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","/**\n * @remarks Time O(n log n), Space O(n).\n * data-structure-typed\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { HeapOptions } from '../../types';\nimport { Heap } from './heap';\n\n/**\n * @template E\n * @template R\n * Min-oriented binary heap.\n * Notes and typical use-cases are documented in {@link Heap}.\n *\n * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.\n * 2. MinHeap Properties: The value of each parent node is less than or equal to the value of its children.\n * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.\n * 7. Efficient Sorting Algorithms: For example, heap sort. MinHeap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum spanning tree algorithm, which use heaps to improve performance.\n * @example\n */\nexport class MinHeap<E = any, R = any> extends Heap<E, R> {\n /**\n * Create a min-heap.\n * @param elements Optional initial elements.\n * @param options Optional configuration.\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: HeapOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { DijkstraResult, EntryCallback, GraphOptions, VertexKey } from '../../types';\nimport { uuidV4 } from '../../utils';\nimport { IterableEntryBase } from '../base';\nimport { IGraph } from '../../interfaces';\nimport { Heap } from '../heap';\nimport { Queue } from '../queue';\n\nexport abstract class AbstractVertex<V = any> {\n key: VertexKey;\n value: V | undefined;\n\n protected constructor(key: VertexKey, value?: V) {\n this.key = key;\n this.value = value;\n }\n}\n\nexport abstract class AbstractEdge<E = any> {\n value: E | undefined;\n weight: number;\n\n protected constructor(weight?: number, value?: E) {\n this.weight = weight !== undefined ? weight : 1;\n this.value = value;\n this._hashCode = uuidV4();\n }\n\n protected _hashCode: string;\n\n get hashCode(): string {\n return this._hashCode;\n }\n}\n\n/**\n * Abstract graph over vertices and edges.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex subclass (extends AbstractVertex<V>).\n * @template EO - Concrete edge subclass (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example examples will be generated by unit test\n */\nexport abstract class AbstractGraph<\n V = any,\n E = any,\n VO extends AbstractVertex<V> = AbstractVertex<V>,\n EO extends AbstractEdge<E> = AbstractEdge<E>\n>\n extends IterableEntryBase<VertexKey, V | undefined>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct a graph with runtime defaults.\n * @param options - `GraphOptions<V>` in `options.graph` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<Record<string, unknown>>) {\n super();\n const graph = (options as any)?.graph as GraphOptions<V> | undefined;\n this._options = { defaultEdgeWeight: 1, ...(graph ?? {}) };\n }\n\n protected _options: GraphOptions<V> = { defaultEdgeWeight: 1 };\n\n get options(): Readonly<GraphOptions<V>> {\n return this._options;\n }\n\n protected _vertexMap: Map<VertexKey, VO> = new Map<VertexKey, VO>();\n\n get vertexMap(): Map<VertexKey, VO> {\n return this._vertexMap;\n }\n\n set vertexMap(v: Map<VertexKey, VO>) {\n this._vertexMap = v;\n }\n\n get size(): number {\n return this._vertexMap.size;\n }\n\n /**\n * Create a new vertex instance (implementation specific).\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n abstract createVertex(key: VertexKey, value?: V): VO;\n\n /**\n * Create a new edge instance (implementation specific).\n * @param srcOrV1 - Source/endpoint A key.\n * @param destOrV2 - Destination/endpoint B key.\n * @param weight - Edge weight (defaults may apply).\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n abstract createEdge(srcOrV1: VertexKey, destOrV2: VertexKey, weight?: number, value?: E): EO;\n\n /**\n * Delete an edge by instance.\n * @param edge - Edge instance.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract deleteEdge(edge: EO): EO | undefined;\n\n /**\n * Get an edge between two vertices if present.\n * @param srcOrKey - Source/endpoint A vertex or key.\n * @param destOrKey - Destination/endpoint B vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract getEdge(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined;\n\n /**\n * Degree of a vertex in this graph model.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer degree.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract degreeOf(vertexOrKey: VO | VertexKey): number;\n\n /**\n * All edges in the graph (unique, order not guaranteed).\n * @returns Array of edges.\n * @remarks Time O(E), Space O(E)\n */\n abstract edgeSet(): EO[];\n\n /**\n * Incident edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg), Space O(deg)\n */\n abstract edgesOf(vertexOrKey: VO | VertexKey): EO[];\n\n /**\n * One-step neighbors of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg), Space O(deg)\n */\n abstract getNeighbors(vertexOrKey: VO | VertexKey): VO[];\n\n /**\n * Resolve endpoints of an edge to vertex instances.\n * @param edge - Edge instance.\n * @returns `[v1, v2]` or `undefined` if missing.\n * @remarks Time O(1), Space O(1)\n */\n abstract getEndsOfEdge(edge: EO): [VO, VO] | undefined;\n\n /**\n * Get vertex instance by key.\n * @param vertexKey - Vertex key.\n * @returns Vertex instance or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n getVertex(vertexKey: VertexKey): VO | undefined {\n return this._vertexMap.get(vertexKey) || undefined;\n }\n\n /**\n * Whether a vertex exists.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if present, otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n hasVertex(vertexOrKey: VO | VertexKey): boolean {\n return this._vertexMap.has(this._getVertexKey(vertexOrKey));\n }\n\n addVertex(vertex: VO): boolean;\n\n addVertex(key: VertexKey, value?: V): boolean;\n\n /**\n * Add a vertex by key/value or by pre-built vertex.\n * @param keyOrVertex - Vertex key or existing vertex instance.\n * @param value - Optional payload.\n * @returns `true` if inserted; `false` when key already exists.\n * @remarks Time O(1) avg, Space O(1)\n */\n addVertex(keyOrVertex: VertexKey | VO, value?: V): boolean {\n if (keyOrVertex instanceof AbstractVertex) {\n return this._addVertex(keyOrVertex);\n } else {\n const newVertex = this.createVertex(keyOrVertex, value);\n return this._addVertex(newVertex);\n }\n }\n\n /**\n * Type guard: check if a value is a valid vertex key.\n * @param potentialKey - Value to test.\n * @returns `true` if string/number; else `false`.\n * @remarks Time O(1), Space O(1)\n */\n isVertexKey(potentialKey: any): potentialKey is VertexKey {\n const potentialKeyType = typeof potentialKey;\n return potentialKeyType === 'string' || potentialKeyType === 'number';\n }\n\n /**\n * Delete a vertex and its incident edges.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if removed; otherwise `false`.\n * @remarks Time O(deg), Space O(1)\n */\n abstract deleteVertex(vertexOrKey: VO | VertexKey): boolean;\n\n /**\n * Delete multiple vertices.\n * @param vertexMap - Array of vertices or keys.\n * @returns `true` if any vertex was removed.\n * @remarks Time O(sum(deg)), Space O(1)\n */\n removeManyVertices(vertexMap: VO[] | VertexKey[]): boolean {\n const removed: boolean[] = [];\n for (const v of vertexMap) {\n removed.push(this.deleteVertex(v));\n }\n return removed.length > 0;\n }\n\n /**\n * Whether an edge exists between two vertices.\n * @param v1 - Endpoint A vertex or key.\n * @param v2 - Endpoint B vertex or key.\n * @returns `true` if present; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n hasEdge(v1: VertexKey | VO, v2: VertexKey | VO): boolean {\n const edge = this.getEdge(v1, v2);\n return !!edge;\n }\n\n addEdge(edge: EO): boolean;\n\n addEdge(src: VO | VertexKey, dest: VO | VertexKey, weight?: number, value?: E): boolean;\n\n /**\n * Add an edge by instance or by `(src, dest, weight?, value?)`.\n * @param srcOrEdge - Edge instance or source vertex/key.\n * @param dest - Destination vertex/key (when adding by pair).\n * @param weight - Edge weight.\n * @param value - Edge payload.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n addEdge(srcOrEdge: VO | VertexKey | EO, dest?: VO | VertexKey, weight?: number, value?: E): boolean {\n if (srcOrEdge instanceof AbstractEdge) {\n return this._addEdge(srcOrEdge);\n } else {\n if (dest instanceof AbstractVertex || typeof dest === 'string' || typeof dest === 'number') {\n if (!(this.hasVertex(srcOrEdge) && this.hasVertex(dest))) return false;\n if (srcOrEdge instanceof AbstractVertex) srcOrEdge = srcOrEdge.key;\n if (dest instanceof AbstractVertex) dest = dest.key;\n const newEdge = this.createEdge(srcOrEdge, dest, weight, value);\n return this._addEdge(newEdge);\n } else {\n throw new Error('dest must be a Vertex or vertex key while srcOrEdge is an Edge');\n }\n }\n }\n\n /**\n * Set the weight of an existing edge.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @param weight - New weight.\n * @returns `true` if updated; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n setEdgeWeight(srcOrKey: VertexKey | VO, destOrKey: VertexKey | VO, weight: number): boolean {\n const edge = this.getEdge(srcOrKey, destOrKey);\n if (edge) {\n edge.weight = weight;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Enumerate simple paths up to a limit.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param limit - Maximum number of paths to collect.\n * @returns Array of paths (each path is an array of vertices).\n * @remarks Time O(paths) worst-case exponential, Space O(V + paths)\n */\n getAllPathsBetween(v1: VO | VertexKey, v2: VO | VertexKey, limit = 1000): VO[][] {\n const paths: VO[][] = [];\n const vertex1 = this._getVertex(v1);\n const vertex2 = this._getVertex(v2);\n\n if (!(vertex1 && vertex2)) {\n return [];\n }\n\n const stack: { vertex: VO; path: VO[] }[] = [];\n stack.push({ vertex: vertex1, path: [vertex1] });\n\n while (stack.length > 0) {\n const { vertex, path } = stack.pop()!;\n\n if (vertex === vertex2) {\n paths.push(path);\n if (paths.length >= limit) return paths;\n }\n\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n if (!path.includes(neighbor)) {\n const newPath = [...path, neighbor];\n stack.push({ vertex: neighbor, path: newPath });\n }\n }\n }\n return paths;\n }\n\n /**\n * Sum the weights along a vertex path.\n * @param path - Sequence of vertices.\n * @returns Path weight sum (0 if empty or edge missing).\n * @remarks Time O(L), Space O(1) where L is path length\n */\n getPathSumWeight(path: VO[]): number {\n let sum = 0;\n for (let i = 0; i < path.length; i++) {\n sum += this.getEdge(path[i], path[i + 1])?.weight || 0;\n }\n return sum;\n }\n\n /**\n * Minimum hops/weight between two vertices.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param isWeight - If `true`, compare by path weight; otherwise by hop count.\n * @returns Minimum cost or `undefined` if missing/unreachable.\n * @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)\n */\n getMinCostBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): number | undefined {\n if (isWeight === undefined) isWeight = false;\n\n if (isWeight) {\n const allPaths = this.getAllPathsBetween(v1, v2);\n let min = Number.MAX_SAFE_INTEGER;\n for (const path of allPaths) {\n min = Math.min(this.getPathSumWeight(path), min);\n }\n return min;\n } else {\n const vertex2 = this._getVertex(v2);\n const vertex1 = this._getVertex(v1);\n if (!(vertex1 && vertex2)) {\n return undefined;\n }\n\n const visited: Map<VO, boolean> = new Map();\n const queue = new Queue<VO>([vertex1]);\n visited.set(vertex1, true);\n let cost = 0;\n while (queue.length > 0) {\n for (let i = 0, layerSize = queue.length; i < layerSize; i++) {\n const cur = queue.shift();\n if (cur === vertex2) {\n return cost;\n }\n\n if (cur !== undefined) {\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n visited.set(neighbor, true);\n queue.push(neighbor);\n }\n }\n }\n }\n cost++;\n }\n return undefined;\n }\n }\n\n /**\n * Minimum path (as vertex sequence) between two vertices.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param isWeight - If `true`, compare by path weight; otherwise by hop count.\n * @param isDFS - For weighted mode only: if `true`, brute-force all paths; if `false`, use Dijkstra.\n * @returns Vertex sequence, or `undefined`/empty when unreachable depending on branch.\n * @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)\n */\n getMinPathBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean, isDFS = false): VO[] | undefined {\n if (isWeight === undefined) isWeight = false;\n\n if (isWeight) {\n if (isDFS) {\n const allPaths = this.getAllPathsBetween(v1, v2, 10000);\n let min = Number.MAX_SAFE_INTEGER;\n let minIndex = -1;\n let index = 0;\n for (const path of allPaths) {\n const pathSumWeight = this.getPathSumWeight(path);\n if (pathSumWeight < min) {\n min = pathSumWeight;\n minIndex = index;\n }\n index++;\n }\n return allPaths[minIndex] || undefined;\n } else {\n /**\n * Dijkstra (binary-heap) shortest paths for non-negative weights.\n * @param src - Source vertex or key.\n * @param dest - Optional destination for early stop.\n * @param getMinDist - If `true`, compute global minimum distance.\n * @param genPaths - If `true`, also generate path arrays.\n * @returns Result bag or `undefined` if source missing.\n * @remarks Time O((V + E) log V), Space O(V + E)\n */\n return this.dijkstra(v1, v2, true, true)?.minPath ?? [];\n }\n } else {\n let minPath: VO[] = [];\n const vertex1 = this._getVertex(v1);\n const vertex2 = this._getVertex(v2);\n if (!(vertex1 && vertex2)) return [];\n\n const dfs = (cur: VO, dest: VO, visiting: Set<VO>, path: VO[]) => {\n visiting.add(cur);\n if (cur === dest) {\n minPath = [vertex1, ...path];\n return;\n }\n\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!visiting.has(neighbor)) {\n path.push(neighbor);\n dfs(neighbor, dest, visiting, path);\n path.pop();\n }\n }\n\n visiting.delete(cur);\n };\n\n dfs(vertex1, vertex2, new Set<VO>(), []);\n return minPath;\n }\n }\n\n /**\n * Dijkstra without heap (array-based selection).\n * @param src - Source vertex or key.\n * @param dest - Optional destination for early stop.\n * @param getMinDist - If `true`, compute global minimum distance.\n * @param genPaths - If `true`, also generate path arrays.\n * @returns Result bag or `undefined` if source missing.\n * @remarks Time O(V^2 + E), Space O(V + E)\n */\n dijkstraWithoutHeap(\n src: VO | VertexKey,\n dest: VO | VertexKey | undefined = undefined,\n getMinDist: boolean = false,\n genPaths: boolean = false\n ): DijkstraResult<VO> | undefined {\n let minDist = Number.MAX_SAFE_INTEGER;\n let minDest: VO | undefined = undefined;\n let minPath: VO[] = [];\n const paths: VO[][] = [];\n\n const vertexMap = this._vertexMap;\n const distMap: Map<VO, number> = new Map();\n const seen: Set<VO> = new Set();\n const preMap: Map<VO, VO | undefined> = new Map();\n const srcVertex = this._getVertex(src);\n\n const destVertex = dest ? this._getVertex(dest) : undefined;\n\n if (!srcVertex) {\n return undefined;\n }\n\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);\n }\n distMap.set(srcVertex, 0);\n preMap.set(srcVertex, undefined);\n\n const getMinOfNoSeen = () => {\n let min = Number.MAX_SAFE_INTEGER;\n let minV: VO | undefined = undefined;\n for (const [key, value] of distMap) {\n if (!seen.has(key)) {\n if (value < min) {\n min = value;\n minV = key;\n }\n }\n }\n return minV;\n };\n\n const getPaths = (minV: VO | undefined) => {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minV) minPath = reversed;\n paths.push(reversed);\n }\n }\n };\n\n for (let i = 1; i < vertexMap.size; i++) {\n const cur = getMinOfNoSeen();\n if (cur) {\n seen.add(cur);\n if (destVertex && destVertex === cur) {\n if (getMinDist) {\n minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;\n }\n if (genPaths) {\n getPaths(destVertex);\n }\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!seen.has(neighbor)) {\n const edge = this.getEdge(cur, neighbor);\n if (edge) {\n const curFromMap = distMap.get(cur);\n const neighborFromMap = distMap.get(neighbor);\n\n if (curFromMap !== undefined && neighborFromMap !== undefined) {\n if (edge.weight + curFromMap < neighborFromMap) {\n distMap.set(neighbor, edge.weight + curFromMap);\n preMap.set(neighbor, cur);\n }\n }\n }\n }\n }\n }\n }\n\n if (getMinDist)\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < minDist) {\n minDist = d;\n if (genPaths) minDest = v;\n }\n }\n });\n\n if (genPaths) getPaths(minDest);\n\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n\n dijkstra(\n src: VO | VertexKey,\n dest: VO | VertexKey | undefined = undefined,\n getMinDist: boolean = false,\n genPaths: boolean = false\n ): DijkstraResult<VO> | undefined {\n let minDist = Number.MAX_SAFE_INTEGER;\n let minDest: VO | undefined = undefined;\n let minPath: VO[] = [];\n const paths: VO[][] = [];\n const vertexMap = this._vertexMap;\n const distMap: Map<VO, number> = new Map();\n const seen: Set<VO> = new Set();\n const preMap: Map<VO, VO | undefined> = new Map();\n\n const srcVertex = this._getVertex(src);\n const destVertex = dest ? this._getVertex(dest) : undefined;\n\n if (!srcVertex) return undefined;\n\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);\n }\n\n const heap = new Heap<{ key: number; value: VO }>([], { comparator: (a, b) => a.key - b.key });\n heap.add({ key: 0, value: srcVertex });\n\n distMap.set(srcVertex, 0);\n preMap.set(srcVertex, undefined);\n\n const getPaths = (minV: VO | undefined) => {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minV) minPath = reversed;\n paths.push(reversed);\n }\n }\n };\n\n while (heap.size > 0) {\n const curHeapNode = heap.poll();\n const dist = curHeapNode?.key;\n const cur = curHeapNode?.value;\n if (dist !== undefined) {\n if (cur) {\n seen.add(cur);\n if (destVertex && destVertex === cur) {\n if (getMinDist) {\n minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;\n }\n if (genPaths) {\n getPaths(destVertex);\n }\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!seen.has(neighbor)) {\n const weight = this.getEdge(cur, neighbor)?.weight;\n if (typeof weight === 'number') {\n const distSrcToNeighbor = distMap.get(neighbor);\n if (distSrcToNeighbor !== undefined) {\n if (dist + weight < distSrcToNeighbor) {\n heap.add({ key: dist + weight, value: neighbor });\n preMap.set(neighbor, cur);\n distMap.set(neighbor, dist + weight);\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (getMinDist) {\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < minDist) {\n minDist = d;\n if (genPaths) minDest = v;\n }\n }\n });\n }\n\n if (genPaths) {\n getPaths(minDest);\n }\n\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n\n /**\n * Bellman-Ford single-source shortest paths with option to scan negative cycles.\n * @param src - Source vertex or key.\n * @param scanNegativeCycle - If `true`, also detect negative cycles.\n * @param getMin - If `true`, compute global minimum distance.\n * @param genPath - If `true`, generate path arrays via predecessor map.\n * @returns Result bag including distances, predecessors, and optional cycle flag.\n * @remarks Time O(V * E), Space O(V + E)\n */\n bellmanFord(src: VO | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) {\n if (getMin === undefined) getMin = false;\n if (genPath === undefined) genPath = false;\n\n const srcVertex = this._getVertex(src);\n const paths: VO[][] = [];\n const distMap: Map<VO, number> = new Map();\n const preMap: Map<VO, VO> = new Map();\n let min = Number.MAX_SAFE_INTEGER;\n let minPath: VO[] = [];\n\n let hasNegativeCycle: boolean | undefined;\n if (scanNegativeCycle) hasNegativeCycle = false;\n if (!srcVertex) return { hasNegativeCycle, distMap, preMap, paths, min, minPath };\n\n const vertexMap = this._vertexMap;\n const numOfVertices = vertexMap.size;\n const edgeMap = this.edgeSet();\n const numOfEdges = edgeMap.length;\n\n this._vertexMap.forEach(vertex => {\n distMap.set(vertex, Number.MAX_SAFE_INTEGER);\n });\n\n distMap.set(srcVertex, 0);\n\n for (let i = 1; i < numOfVertices; ++i) {\n for (let j = 0; j < numOfEdges; ++j) {\n const ends = this.getEndsOfEdge(edgeMap[j]);\n if (ends) {\n const [s, d] = ends;\n const weight = edgeMap[j].weight;\n const sWeight = distMap.get(s);\n const dWeight = distMap.get(d);\n if (sWeight !== undefined && dWeight !== undefined) {\n if (distMap.get(s) !== Number.MAX_SAFE_INTEGER && sWeight + weight < dWeight) {\n distMap.set(d, sWeight + weight);\n if (genPath) preMap.set(d, s);\n }\n }\n }\n }\n }\n\n let minDest: VO | undefined = undefined;\n if (getMin) {\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < min) {\n min = d;\n if (genPath) minDest = v;\n }\n }\n });\n }\n\n if (genPath) {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent !== undefined) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minDest) minPath = reversed;\n paths.push(reversed);\n }\n }\n }\n\n for (let j = 0; j < numOfEdges; ++j) {\n const ends = this.getEndsOfEdge(edgeMap[j]);\n if (ends) {\n const [s] = ends;\n const weight = edgeMap[j].weight;\n const sWeight = distMap.get(s);\n if (sWeight) {\n if (sWeight !== Number.MAX_SAFE_INTEGER && sWeight + weight < sWeight) hasNegativeCycle = true;\n }\n }\n }\n\n return { hasNegativeCycle, distMap, preMap, paths, min, minPath };\n }\n\n /**\n * Floyd–Warshall all-pairs shortest paths.\n * @returns `{ costs, predecessor }` matrices.\n * @remarks Time O(V^3), Space O(V^2)\n */\n floydWarshall(): { costs: number[][]; predecessor: (VO | undefined)[][] } {\n const idAndVertices = [...this._vertexMap];\n const n = idAndVertices.length;\n\n const costs: number[][] = [];\n const predecessor: (VO | undefined)[][] = [];\n\n for (let i = 0; i < n; i++) {\n costs[i] = [];\n predecessor[i] = [];\n for (let j = 0; j < n; j++) {\n predecessor[i][j] = undefined;\n }\n }\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Number.MAX_SAFE_INTEGER;\n }\n }\n\n for (let k = 0; k < n; k++) {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (costs[i][j] > costs[i][k] + costs[k][j]) {\n costs[i][j] = costs[i][k] + costs[k][j];\n predecessor[i][j] = idAndVertices[k][1];\n }\n }\n }\n }\n return { costs, predecessor };\n }\n\n /**\n * Enumerate simple cycles (may be expensive).\n * @param isInclude2Cycle - If `true`, include 2-cycles when graph semantics allow.\n * @returns Array of cycles (each as array of vertex keys).\n * @remarks Time exponential in worst-case, Space O(V + E)\n */\n getCycles(isInclude2Cycle: boolean = false): VertexKey[][] {\n const cycles: VertexKey[][] = [];\n const visited: Set<VO> = new Set();\n\n const dfs = (vertex: VO, currentPath: VertexKey[], visited: Set<VO>) => {\n if (visited.has(vertex)) {\n if (\n ((!isInclude2Cycle && currentPath.length > 2) || (isInclude2Cycle && currentPath.length >= 2)) &&\n currentPath[0] === vertex.key\n ) {\n cycles.push([...currentPath]);\n }\n return;\n }\n\n visited.add(vertex);\n currentPath.push(vertex.key);\n\n for (const neighbor of this.getNeighbors(vertex)) {\n if (neighbor) dfs(neighbor, currentPath, visited);\n }\n\n visited.delete(vertex);\n currentPath.pop();\n };\n\n for (const vertex of this.vertexMap.values()) {\n dfs(vertex, [], visited);\n }\n\n const uniqueCycles = new Map<string, VertexKey[]>();\n\n for (const cycle of cycles) {\n const sorted = [...cycle].sort().toString();\n\n if (uniqueCycles.has(sorted)) continue;\n else {\n uniqueCycles.set(sorted, cycle);\n }\n }\n\n /**\n * Map entries to an array via callback.\n * @param callback - `(key, value, index, self) => T`.\n * @param thisArg - Optional `this` for callback.\n * @returns Mapped results.\n * @remarks Time O(V), Space O(V)\n */\n return [...uniqueCycles].map(cycleString => cycleString[1]);\n }\n\n /**\n * Induced-subgraph filter: keep vertices where `predicate(key, value)` is true,\n * and only keep edges whose endpoints both survive.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n filter(predicate: EntryCallback<VertexKey, V | undefined, boolean>, thisArg?: any): this {\n const filtered: [VertexKey, V | undefined][] = [];\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, value, key, index, this)) {\n filtered.push([key, value]);\n }\n index++;\n }\n return this._createLike(filtered, this._snapshotOptions());\n }\n\n /**\n * Preserve the old behavior: return filtered entries as an array.\n * @remarks Time O(V), Space O(V)\n */\n filterEntries(\n predicate: EntryCallback<VertexKey, V | undefined, boolean>,\n thisArg?: any\n ): [VertexKey, V | undefined][] {\n const filtered: [VertexKey, V | undefined][] = [];\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, value, key, index, this)) {\n filtered.push([key, value]);\n }\n index++;\n }\n return filtered;\n }\n\n map<T>(callback: EntryCallback<VertexKey, V | undefined, T>, thisArg?: any): T[] {\n const mapped: T[] = [];\n let index = 0;\n for (const [key, value] of this) {\n mapped.push(callback.call(thisArg, value, key, index, this));\n index++;\n }\n return mapped;\n }\n\n /**\n * Create a deep clone of the graph with the same species.\n * @remarks Time O(V + E), Space O(V + E)\n */\n /**\n * Create a deep clone of the graph with the same species.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n clone(): this {\n return this._createLike(undefined, this._snapshotOptions());\n }\n\n // ===== Same-species factory & cloning helpers =====\n\n /**\n * Internal iterator over `[key, value]` entries in insertion order.\n * @returns Iterator of `[VertexKey, V | undefined]`.\n * @remarks Time O(V), Space O(1)\n */\n protected *_getIterator(): IterableIterator<[VertexKey, V | undefined]> {\n for (const vertex of this._vertexMap.values()) {\n yield [vertex.key, vertex.value];\n }\n }\n\n /**\n * Capture configuration needed to reproduce the current graph.\n * Currently the graph has no runtime options, so we return an empty object.\n */\n /**\n * Capture configuration needed to reproduce the current graph.\n * @returns Options bag (opaque to callers).\n * @remarks Time O(1), Space O(1)\n */\n protected _snapshotOptions(): Record<string, unknown> {\n return { graph: { ...this._options } };\n }\n\n /**\n * Create an empty graph instance of the same concrete species (Directed/Undirected/etc).\n * @remarks Time O(1), Space O(1)\n */\n /**\n * Create an empty graph instance of the same concrete species.\n * @param _options - Snapshot options from `_snapshotOptions()`.\n * @returns A new empty graph instance of `this` type.\n * @remarks Time O(1), Space O(1)\n */\n protected _createInstance(_options?: Partial<Record<string, unknown>>): this {\n const Ctor: any = (this as any).constructor;\n const instance: this = new Ctor();\n const graph = (_options as any)?.graph as GraphOptions<V> | undefined;\n if (graph) (instance as any)._options = { ...(instance as any)._options, ...graph };\n else (instance as any)._options = { ...(instance as any)._options, ...(this as any)._options };\n return instance;\n }\n\n /**\n * Create a same-species graph populated with the given entries.\n * Also preserves edges between kept vertices from the source graph.\n * @remarks Time O(V + E), Space O(V + E)\n */\n /**\n * Create a same-species graph populated with entries; preserves edges among kept vertices.\n * @param iter - Optional entries to seed the new graph.\n * @param options - Snapshot options.\n * @returns A new graph of `this` type.\n * @remarks Time O(V + E), Space O(V + E)\n */\n protected _createLike(iter?: Iterable<[VertexKey, V | undefined]>, options?: Partial<Record<string, unknown>>): this {\n const g = this._createInstance(options);\n // 1) Add vertices\n if (iter) {\n for (const [k, v] of iter) {\n (g as any).addVertex(k as VertexKey, v as V | undefined);\n }\n } else {\n for (const [k, v] of this) {\n (g as any).addVertex(k as VertexKey, v as V | undefined);\n }\n }\n // 2) Add edges whose endpoints exist in the new graph\n const edges = this.edgeSet();\n for (const e of edges as any[]) {\n const ends = this.getEndsOfEdge(e as any) as unknown as [any, any] | undefined;\n if (!ends) continue;\n const [va, vb] = ends;\n const ka = (va as any).key as VertexKey;\n const kb = (vb as any).key as VertexKey;\n const hasA = (g as any).hasVertex ? (g as any).hasVertex(ka) : false;\n const hasB = (g as any).hasVertex ? (g as any).hasVertex(kb) : false;\n if (hasA && hasB) {\n const w = (e as any).weight;\n const val = (e as any).value;\n const newEdge = (g as any).createEdge(ka, kb, w, val);\n (g as any)._addEdge(newEdge);\n }\n }\n return g;\n }\n\n /**\n * Internal hook to attach an edge into adjacency structures.\n * @param edge - Edge instance.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected abstract _addEdge(edge: EO): boolean;\n\n /**\n * Insert a pre-built vertex into the graph.\n * @param newVertex - Concrete vertex instance.\n * @returns `true` if inserted; `false` if key already exists.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addVertex(newVertex: VO): boolean {\n if (this.hasVertex(newVertex)) {\n return false;\n }\n this._vertexMap.set(newVertex.key, newVertex);\n return true;\n }\n\n /**\n * Resolve a vertex key or instance to the concrete vertex instance.\n * @param vertexOrKey - Vertex key or existing vertex.\n * @returns Vertex instance or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n protected _getVertex(vertexOrKey: VertexKey | VO): VO | undefined {\n const vertexKey = this._getVertexKey(vertexOrKey);\n return this._vertexMap.get(vertexKey) || undefined;\n }\n\n /**\n * Resolve a vertex key from a key or vertex instance.\n * @param vertexOrKey - Vertex key or existing vertex.\n * @returns The vertex key.\n * @remarks Time O(1), Space O(1)\n */\n protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey {\n return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { GraphOptions, TopologicalStatus, VertexKey } from '../../types';\nimport { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';\nimport { IGraph } from '../../interfaces';\nimport { arrayRemove } from '../../utils';\n\nexport class DirectedVertex<V = any> extends AbstractVertex<V> {\n constructor(key: VertexKey, value?: V) {\n super(key, value);\n }\n}\n\nexport class DirectedEdge<E = any> extends AbstractEdge<E> {\n src: VertexKey;\n dest: VertexKey;\n\n constructor(src: VertexKey, dest: VertexKey, weight?: number, value?: E) {\n super(weight, value);\n this.src = src;\n this.dest = dest;\n }\n}\n\n/**\n * Directed graph implementation.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (extends AbstractVertex<V>).\n * @template EO - Concrete edge class (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example\n * // basic DirectedGraph vertex and edge creation\n * // Create a simple directed graph\n * const graph = new DirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n *\n * // Verify vertices exist\n * console.log(graph.hasVertex('A')); // true;\n * console.log(graph.hasVertex('B')); // true;\n * console.log(graph.hasVertex('C')); // true;\n * console.log(graph.hasVertex('D')); // false;\n *\n * // Check vertex count\n * console.log(graph.size); // 3;\n * @example\n * // DirectedGraph edge operations\n * const graph = new DirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n *\n * // Add directed edges\n * graph.addEdge('A', 'B', 1);\n * graph.addEdge('B', 'C', 2);\n * graph.addEdge('A', 'C', 3);\n *\n * // Verify edges exist\n * console.log(graph.hasEdge('A', 'B')); // true;\n * console.log(graph.hasEdge('B', 'C')); // true;\n * console.log(graph.hasEdge('C', 'B')); // false; // Graph is directed\n *\n * // Get neighbors of A\n * const neighborsA = graph.getNeighbors('A');\n * console.log(neighborsA[0].key); // 'B';\n * console.log(neighborsA[1].key); // 'C';\n * @example\n * // DirectedGraph deleteEdge and vertex operations\n * const graph = new DirectedGraph<string>();\n *\n * // Build a small graph\n * graph.addVertex('X');\n * graph.addVertex('Y');\n * graph.addVertex('Z');\n * graph.addEdge('X', 'Y', 1);\n * graph.addEdge('Y', 'Z', 2);\n *\n * // Delete an edge\n * graph.deleteEdgeSrcToDest('X', 'Y');\n * console.log(graph.hasEdge('X', 'Y')); // false;\n *\n * // Edge in other direction should not exist\n * console.log(graph.hasEdge('Y', 'X')); // false;\n *\n * // Other edges should remain\n * console.log(graph.hasEdge('Y', 'Z')); // true;\n *\n * // Delete a vertex\n * graph.deleteVertex('Y');\n * console.log(graph.hasVertex('Y')); // false;\n * console.log(graph.size); // 2;\n * @example\n * // DirectedGraph topologicalSort for task scheduling\n * const graph = new DirectedGraph<string>();\n *\n * // Build a DAG (Directed Acyclic Graph) for task dependencies\n * graph.addVertex('Design');\n * graph.addVertex('Implement');\n * graph.addVertex('Test');\n * graph.addVertex('Deploy');\n *\n * // Add dependency edges\n * graph.addEdge('Design', 'Implement', 1); // Design must come before Implement\n * graph.addEdge('Implement', 'Test', 1); // Implement must come before Test\n * graph.addEdge('Test', 'Deploy', 1); // Test must come before Deploy\n *\n * // Topological sort gives valid execution order\n * const executionOrder = graph.topologicalSort();\n * console.log(executionOrder); // defined;\n * console.log(executionOrder); // ['Design', 'Implement', 'Test', 'Deploy'];\n *\n * // All vertices should be included\n * console.log(executionOrder?.length); // 4;\n * @example\n * // DirectedGraph dijkstra shortest path for network routing\n * // Build a weighted directed graph representing network nodes and costs\n * const network = new DirectedGraph<string>();\n *\n * // Add network nodes\n * network.addVertex('Router-A');\n * network.addVertex('Router-B');\n * network.addVertex('Router-C');\n * network.addVertex('Router-D');\n * network.addVertex('Router-E');\n *\n * // Add weighted edges (network latency costs)\n * network.addEdge('Router-A', 'Router-B', 5);\n * network.addEdge('Router-A', 'Router-C', 10);\n * network.addEdge('Router-B', 'Router-D', 3);\n * network.addEdge('Router-C', 'Router-D', 2);\n * network.addEdge('Router-D', 'Router-E', 4);\n * network.addEdge('Router-B', 'Router-E', 12);\n *\n * // Find shortest path from Router-A to Router-E\n * const { minDist, minPath } = network.dijkstra('Router-A', 'Router-E', true, true) || {\n * minDist: undefined,\n * minPath: undefined\n * };\n *\n * // Verify shortest path is found\n * console.log(minDist); // defined;\n * console.log(minPath); // defined;\n *\n * // Shortest path should be A -> B -> D -> E with cost 5+3+4=12\n * // Or A -> C -> D -> E with cost 10+2+4=16\n * // So the minimum is 12\n * console.log(minDist); // <= 16;\n *\n * // Verify path is valid (includes start and end)\n * console.log(minPath?.[0].key); // 'Router-A';\n * console.log(minPath?.[minPath.length - 1].key); // 'Router-E';\n */\nexport class DirectedGraph<\n V = any,\n E = any,\n VO extends DirectedVertex<V> = DirectedVertex<V>,\n EO extends DirectedEdge<E> = DirectedEdge<E>\n>\n extends AbstractGraph<V, E, VO, EO>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct a directed graph with runtime defaults.\n * @param options - `GraphOptions<V>` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<GraphOptions<V>>) {\n super(options);\n }\n\n protected _outEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();\n\n get outEdgeMap(): Map<VO, EO[]> {\n return this._outEdgeMap;\n }\n\n set outEdgeMap(v: Map<VO, EO[]>) {\n this._outEdgeMap = v;\n }\n\n protected _inEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();\n\n get inEdgeMap(): Map<VO, EO[]> {\n return this._inEdgeMap;\n }\n\n set inEdgeMap(v: Map<VO, EO[]>) {\n this._inEdgeMap = v;\n }\n\n /**\n * Construct a directed graph from keys with value initializer `v => v`.\n * @template K - Vertex key type.\n * @param keys - Iterable of vertex keys.\n * @returns DirectedGraph with all keys added.\n * @remarks Time O(V), Space O(V)\n */\n static fromKeys<K extends VertexKey>(keys: Iterable<K>): DirectedGraph<K, any, DirectedVertex<K>, DirectedEdge<any>> {\n const g: DirectedGraph<K, any, DirectedVertex<K>, DirectedEdge<any>> = new DirectedGraph<K, any>({\n vertexValueInitializer: (k: VertexKey) => k as K\n });\n for (const k of keys) g.addVertex(k);\n return g;\n }\n\n /**\n * Construct a directed graph from `[key, value]` entries.\n * @template V - Vertex value type.\n * @param entries - Iterable of `[key, value]` pairs.\n * @returns DirectedGraph with all vertices added.\n * @remarks Time O(V), Space O(V)\n */\n static fromEntries<V>(\n entries: Iterable<[VertexKey, V]>\n ): DirectedGraph<V, any, DirectedVertex<V>, DirectedEdge<any>> {\n const g: DirectedGraph<V, any, DirectedVertex<V>, DirectedEdge<any>> = new DirectedGraph<V, any>();\n for (const [k, v] of entries) g.addVertex(k, v);\n return g;\n }\n\n /**\n * Create a directed vertex instance. Does not insert into the graph.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n createVertex(key: VertexKey, value?: VO['value']): VO {\n return new DirectedVertex(key, value) as VO;\n }\n\n /**\n * Create a directed edge instance. Does not insert into the graph.\n * @param src - Source vertex key.\n * @param dest - Destination vertex key.\n * @param weight - Edge weight; defaults to `defaultEdgeWeight`.\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n createEdge(src: VertexKey, dest: VertexKey, weight?: number, value?: E): EO {\n return new DirectedEdge(src, dest, weight ?? this.options.defaultEdgeWeight ?? 1, value) as EO;\n }\n\n /**\n * Get the unique edge from `src` to `dest`, if present.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n getEdge(srcOrKey: VO | VertexKey | undefined, destOrKey: VO | VertexKey | undefined): EO | undefined {\n let edgeMap: EO[] = [];\n\n if (srcOrKey !== undefined && destOrKey !== undefined) {\n const src: VO | undefined = this._getVertex(srcOrKey);\n const dest: VO | undefined = this._getVertex(destOrKey);\n\n if (src && dest) {\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges) {\n edgeMap = srcOutEdges.filter(edge => edge.dest === dest.key);\n }\n }\n }\n\n return edgeMap[0] || undefined;\n }\n\n /**\n * Delete edge `src -> dest` if present.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdgeSrcToDest(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined {\n const src: VO | undefined = this._getVertex(srcOrKey);\n const dest: VO | undefined = this._getVertex(destOrKey);\n let removed: EO | undefined = undefined;\n if (!src || !dest) {\n return undefined;\n }\n\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges) {\n arrayRemove<EO>(srcOutEdges, (edge: EO) => edge.dest === dest.key);\n }\n\n const destInEdges = this._inEdgeMap.get(dest);\n if (destInEdges) {\n removed = arrayRemove<EO>(destInEdges, (edge: EO) => edge.src === src.key)[0] || undefined;\n }\n return removed;\n }\n\n /**\n * Delete an edge by instance or by `(srcKey, destKey)`.\n * @param edgeOrSrcVertexKey - Edge instance or source vertex/key.\n * @param destVertexKey - Optional destination vertex/key when deleting by pair.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdge(edgeOrSrcVertexKey: EO | VertexKey, destVertexKey?: VertexKey): EO | undefined {\n let removed: EO | undefined = undefined;\n let src: VO | undefined, dest: VO | undefined;\n if (this.isVertexKey(edgeOrSrcVertexKey)) {\n if (this.isVertexKey(destVertexKey)) {\n src = this._getVertex(edgeOrSrcVertexKey);\n dest = this._getVertex(destVertexKey);\n } else {\n return;\n }\n } else {\n src = this._getVertex(edgeOrSrcVertexKey.src);\n dest = this._getVertex(edgeOrSrcVertexKey.dest);\n }\n\n if (src && dest) {\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges && srcOutEdges.length > 0) {\n arrayRemove(srcOutEdges, (edge: EO) => edge.src === src!.key && edge.dest === dest?.key);\n }\n\n const destInEdges = this._inEdgeMap.get(dest);\n if (destInEdges && destInEdges.length > 0) {\n removed = arrayRemove(destInEdges, (edge: EO) => edge.src === src!.key && edge.dest === dest!.key)[0];\n }\n }\n\n return removed;\n }\n\n deleteVertex(vertexOrKey: VO | VertexKey): boolean {\n let vertexKey: VertexKey;\n let vertex: VO | undefined;\n if (this.isVertexKey(vertexOrKey)) {\n vertex = this.getVertex(vertexOrKey);\n vertexKey = vertexOrKey;\n } else {\n vertex = vertexOrKey;\n vertexKey = this._getVertexKey(vertexOrKey);\n }\n\n if (vertex) {\n /**\n * One-step neighbors following outgoing edges.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n this.deleteEdgeSrcToDest(vertex, neighbor);\n }\n this._outEdgeMap.delete(vertex);\n this._inEdgeMap.delete(vertex);\n }\n\n return this._vertexMap.delete(vertexKey);\n }\n\n deleteEdgesBetween(v1: VertexKey | VO, v2: VertexKey | VO): EO[] {\n const removed: EO[] = [];\n\n if (v1 && v2) {\n const v1ToV2 = this.deleteEdgeSrcToDest(v1, v2);\n const v2ToV1 = this.deleteEdgeSrcToDest(v2, v1);\n\n if (v1ToV2) removed.push(v1ToV2);\n if (v2ToV1) removed.push(v2ToV1);\n }\n\n return removed;\n }\n\n /**\n * Incoming edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incoming edges.\n * @remarks Time O(deg_in), Space O(deg_in)\n */\n incomingEdgesOf(vertexOrKey: VO | VertexKey): EO[] {\n const target = this._getVertex(vertexOrKey);\n if (target) {\n return this.inEdgeMap.get(target) || [];\n }\n return [];\n }\n\n /**\n * Outgoing edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of outgoing edges.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n outgoingEdgesOf(vertexOrKey: VO | VertexKey): EO[] {\n const target = this._getVertex(vertexOrKey);\n if (target) {\n return this._outEdgeMap.get(target) || [];\n }\n return [];\n }\n\n /**\n * Degree (in + out) of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n degreeOf(vertexOrKey: VertexKey | VO): number {\n /**\n * In-degree of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n /**\n * Out-degree of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n return this.outDegreeOf(vertexOrKey) + this.inDegreeOf(vertexOrKey);\n }\n\n inDegreeOf(vertexOrKey: VertexKey | VO): number {\n return this.incomingEdgesOf(vertexOrKey).length;\n }\n\n outDegreeOf(vertexOrKey: VertexKey | VO): number {\n return this.outgoingEdgesOf(vertexOrKey).length;\n }\n\n /**\n * All incident edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg_in + deg_out), Space O(deg_in + deg_out)\n */\n edgesOf(vertexOrKey: VertexKey | VO): EO[] {\n return [...this.outgoingEdgesOf(vertexOrKey), ...this.incomingEdgesOf(vertexOrKey)];\n }\n\n getEdgeSrc(e: EO): VO | undefined {\n return this._getVertex(e.src);\n }\n\n getEdgeDest(e: EO): VO | undefined {\n return this._getVertex(e.dest);\n }\n\n /**\n * Direct children reachable by one outgoing edge.\n * @param vertex - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n getDestinations(vertex: VO | VertexKey | undefined): VO[] {\n if (vertex === undefined) {\n return [];\n }\n const destinations: VO[] = [];\n const outgoingEdges = this.outgoingEdgesOf(vertex);\n for (const outEdge of outgoingEdges) {\n const child = this.getEdgeDest(outEdge);\n if (child) {\n destinations.push(child);\n }\n }\n return destinations;\n }\n\n /**\n * Topological sort if DAG; returns `undefined` if a cycle exists.\n * @param propertyName - `'key'` to map to keys; `'vertex'` to keep instances.\n * @returns Array of keys/vertices, or `undefined` when cycle is found.\n * @remarks Time O(V + E), Space O(V)\n */\n topologicalSort(propertyName?: 'vertex' | 'key'): Array<VO | VertexKey> | undefined {\n propertyName = propertyName ?? 'key';\n\n const statusMap: Map<VO | VertexKey, TopologicalStatus> = new Map<VO | VertexKey, TopologicalStatus>();\n for (const entry of this.vertexMap) {\n statusMap.set(entry[1], 0);\n }\n\n let sorted: (VO | VertexKey)[] = [];\n let hasCycle = false;\n const dfs = (cur: VO | VertexKey) => {\n statusMap.set(cur, 1);\n const children = this.getDestinations(cur);\n for (const child of children) {\n const childStatus = statusMap.get(child);\n if (childStatus === 0) {\n dfs(child);\n } else if (childStatus === 1) {\n hasCycle = true;\n }\n }\n statusMap.set(cur, 2);\n sorted.push(cur);\n };\n\n for (const entry of this.vertexMap) {\n if (statusMap.get(entry[1]) === 0) {\n dfs(entry[1]);\n }\n }\n\n if (hasCycle) return undefined;\n\n if (propertyName === 'key') sorted = sorted.map(vertex => (vertex instanceof DirectedVertex ? vertex.key : vertex));\n return sorted.reverse();\n }\n\n edgeSet(): EO[] {\n let edgeMap: EO[] = [];\n this._outEdgeMap.forEach(outEdges => {\n edgeMap = [...edgeMap, ...outEdges];\n });\n return edgeMap;\n }\n\n getNeighbors(vertexOrKey: VO | VertexKey): VO[] {\n const neighbors: VO[] = [];\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n const outEdges = this.outgoingEdgesOf(vertex);\n for (const outEdge of outEdges) {\n const neighbor = this._getVertex(outEdge.dest);\n\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n }\n return neighbors;\n }\n\n /**\n * Resolve an edge's `[src, dest]` endpoints to vertex instances.\n * @param edge - Edge instance.\n * @returns `[src, dest]` or `undefined` if either endpoint is missing.\n * @remarks Time O(1), Space O(1)\n */\n getEndsOfEdge(edge: EO): [VO, VO] | undefined {\n if (!this.hasEdge(edge.src, edge.dest)) {\n return undefined;\n }\n const v1 = this._getVertex(edge.src);\n const v2 = this._getVertex(edge.dest);\n if (v1 && v2) {\n return [v1, v2];\n } else {\n return undefined;\n }\n }\n\n /**\n * Whether the graph has no vertices and no edges.\n * @remarks Time O(1), Space O(1)\n */\n isEmpty(): boolean {\n return this.vertexMap.size === 0 && this.inEdgeMap.size === 0 && this.outEdgeMap.size === 0;\n }\n\n /**\n * Remove all vertices and edges.\n * @remarks Time O(V + E), Space O(1)\n */\n clear() {\n this._vertexMap = new Map<VertexKey, VO>();\n this._inEdgeMap = new Map<VO, EO[]>();\n this._outEdgeMap = new Map<VO, EO[]>();\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Tarjan's algorithm for strongly connected components.\n * @returns `{ dfnMap, lowMap, SCCs }`.\n * @remarks Time O(V + E), Space O(V + E)\n */\n tarjan(): { dfnMap: Map<VO, number>; lowMap: Map<VO, number>; SCCs: Map<number, VO[]> } {\n const dfnMap = new Map<VO, number>();\n const lowMap = new Map<VO, number>();\n const SCCs = new Map<number, VO[]>();\n\n let time = 0;\n\n const stack: VO[] = [];\n const inStack: Set<VO> = new Set();\n\n const dfs = (vertex: VO) => {\n dfnMap.set(vertex, time);\n lowMap.set(vertex, time);\n time++;\n\n stack.push(vertex);\n inStack.add(vertex);\n\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n if (!dfnMap.has(neighbor)) {\n dfs(neighbor);\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, lowMap.get(neighbor)!));\n } else if (inStack.has(neighbor)) {\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, dfnMap.get(neighbor)!));\n }\n }\n\n if (dfnMap.get(vertex) === lowMap.get(vertex)) {\n const SCC: VO[] = [];\n let poppedVertex: VO | undefined;\n\n do {\n poppedVertex = stack.pop();\n inStack.delete(poppedVertex!);\n SCC.push(poppedVertex!);\n } while (poppedVertex !== vertex);\n\n SCCs.set(SCCs.size, SCC);\n }\n };\n\n for (const vertex of this.vertexMap.values()) {\n if (!dfnMap.has(vertex)) {\n dfs(vertex);\n }\n }\n\n return { dfnMap, lowMap, SCCs };\n }\n\n /**\n * DFN index map computed by `tarjan()`.\n * @returns Map from vertex to DFN index.\n * @remarks Time O(V), Space O(V)\n */\n getDFNMap(): Map<VO, number> {\n return this.tarjan().dfnMap;\n }\n\n /**\n * LOW link map computed by `tarjan()`.\n * @returns Map from vertex to LOW value.\n * @remarks Time O(V), Space O(V)\n */\n getLowMap(): Map<VO, number> {\n return this.tarjan().lowMap;\n }\n\n /**\n * Strongly connected components computed by `tarjan()`.\n * @returns Map from SCC id to vertices.\n * @remarks Time O(#SCC + V), Space O(V)\n */\n getSCCs(): Map<number, VO[]> {\n return this.tarjan().SCCs;\n }\n\n /**\n * Internal hook to attach a directed edge into adjacency maps.\n * @param edge - Edge instance.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addEdge(edge: EO): boolean {\n if (!(this.hasVertex(edge.src) && this.hasVertex(edge.dest))) {\n return false;\n }\n\n const srcVertex = this._getVertex(edge.src);\n const destVertex = this._getVertex(edge.dest);\n\n if (srcVertex && destVertex) {\n const srcOutEdges = this._outEdgeMap.get(srcVertex);\n if (srcOutEdges) {\n srcOutEdges.push(edge);\n } else {\n this._outEdgeMap.set(srcVertex, [edge]);\n }\n\n const destInEdges = this._inEdgeMap.get(destVertex);\n if (destInEdges) {\n destInEdges.push(edge);\n } else {\n this._inEdgeMap.set(destVertex, [edge]);\n }\n return true;\n } else {\n return false;\n }\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { GraphOptions, VertexKey } from '../../types';\nimport { IGraph } from '../../interfaces';\nimport { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';\nimport { arrayRemove } from '../../utils';\n\nexport class UndirectedVertex<V = any> extends AbstractVertex<V> {\n constructor(key: VertexKey, value?: V) {\n super(key, value);\n }\n}\n\nexport class UndirectedEdge<E = number> extends AbstractEdge<E> {\n endpoints: [VertexKey, VertexKey];\n\n constructor(v1: VertexKey, v2: VertexKey, weight?: number, value?: E) {\n super(weight, value);\n this.endpoints = [v1, v2];\n }\n}\n\n/**\n * Undirected graph implementation.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (extends AbstractVertex<V>).\n * @template EO - Concrete edge class (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example\n * // basic UndirectedGraph vertex and edge creation\n * // Create a simple undirected graph\n * const graph = new UndirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n * graph.addVertex('D');\n *\n * // Verify vertices exist\n * console.log(graph.hasVertex('A')); // true;\n * console.log(graph.hasVertex('B')); // true;\n * console.log(graph.hasVertex('E')); // false;\n *\n * // Check vertex count\n * console.log(graph.size); // 4;\n * @example\n * // UndirectedGraph edge operations (bidirectional)\n * const graph = new UndirectedGraph<string>();\n *\n * // Add vertices\n * graph.addVertex('A');\n * graph.addVertex('B');\n * graph.addVertex('C');\n *\n * // Add undirected edges (both directions automatically)\n * graph.addEdge('A', 'B', 1);\n * graph.addEdge('B', 'C', 2);\n * graph.addEdge('A', 'C', 3);\n *\n * // Verify edges exist in both directions\n * console.log(graph.hasEdge('A', 'B')); // true;\n * console.log(graph.hasEdge('B', 'A')); // true; // Bidirectional!\n *\n * console.log(graph.hasEdge('C', 'B')); // true;\n * console.log(graph.hasEdge('B', 'C')); // true; // Bidirectional!\n *\n * // Get neighbors of A\n * const neighborsA = graph.getNeighbors('A');\n * console.log(neighborsA[0].key); // 'B';\n * console.log(neighborsA[1].key); // 'C';\n * @example\n * // UndirectedGraph deleteEdge and vertex operations\n * const graph = new UndirectedGraph<string>();\n *\n * // Build a simple undirected graph\n * graph.addVertex('X');\n * graph.addVertex('Y');\n * graph.addVertex('Z');\n * graph.addEdge('X', 'Y', 1);\n * graph.addEdge('Y', 'Z', 2);\n * graph.addEdge('X', 'Z', 3);\n *\n * // Delete an edge\n * graph.deleteEdge('X', 'Y');\n * console.log(graph.hasEdge('X', 'Y')); // false;\n *\n * // Bidirectional deletion confirmed\n * console.log(graph.hasEdge('Y', 'X')); // false;\n *\n * // Other edges should remain\n * console.log(graph.hasEdge('Y', 'Z')); // true;\n * console.log(graph.hasEdge('Z', 'Y')); // true;\n *\n * // Delete a vertex\n * graph.deleteVertex('Y');\n * console.log(graph.hasVertex('Y')); // false;\n * console.log(graph.size); // 2;\n * @example\n * // UndirectedGraph connectivity and neighbors\n * const graph = new UndirectedGraph<string>();\n *\n * // Build a friendship network\n * const people = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'];\n * for (const person of people) {\n * graph.addVertex(person);\n * }\n *\n * // Add friendships (undirected edges)\n * graph.addEdge('Alice', 'Bob', 1);\n * graph.addEdge('Alice', 'Charlie', 1);\n * graph.addEdge('Bob', 'Diana', 1);\n * graph.addEdge('Charlie', 'Eve', 1);\n * graph.addEdge('Diana', 'Eve', 1);\n *\n * // Get friends of each person\n * const aliceFriends = graph.getNeighbors('Alice');\n * console.log(aliceFriends[0].key); // 'Bob';\n * console.log(aliceFriends[1].key); // 'Charlie';\n * console.log(aliceFriends.length); // 2;\n *\n * const dianaFriends = graph.getNeighbors('Diana');\n * console.log(dianaFriends[0].key); // 'Bob';\n * console.log(dianaFriends[1].key); // 'Eve';\n * console.log(dianaFriends.length); // 2;\n *\n * // Verify bidirectional friendship\n * const bobFriends = graph.getNeighbors('Bob');\n * console.log(bobFriends[0].key); // 'Alice'; // Alice -> Bob -> Alice ✓\n * console.log(bobFriends[1].key); // 'Diana';\n * @example\n * // UndirectedGraph for social network connectivity analysis\n * interface Person {\n * id: number;\n * name: string;\n * location: string;\n * }\n *\n * // UndirectedGraph is perfect for modeling symmetric relationships\n * // (friendships, collaborations, partnerships)\n * const socialNetwork = new UndirectedGraph<number, Person>();\n *\n * // Add people as vertices\n * const people: [number, Person][] = [\n * [1, { id: 1, name: 'Alice', location: 'New York' }],\n * [2, { id: 2, name: 'Bob', location: 'San Francisco' }],\n * [3, { id: 3, name: 'Charlie', location: 'Boston' }],\n * [4, { id: 4, name: 'Diana', location: 'New York' }],\n * [5, { id: 5, name: 'Eve', location: 'Seattle' }]\n * ];\n *\n * for (const [id] of people) {\n * socialNetwork.addVertex(id);\n * }\n *\n * // Add friendships (automatically bidirectional)\n * socialNetwork.addEdge(1, 2, 1); // Alice <-> Bob\n * socialNetwork.addEdge(1, 3, 1); // Alice <-> Charlie\n * socialNetwork.addEdge(2, 4, 1); // Bob <-> Diana\n * socialNetwork.addEdge(3, 5, 1); // Charlie <-> Eve\n * socialNetwork.addEdge(4, 5, 1); // Diana <-> Eve\n *\n * console.log(socialNetwork.size); // 5;\n *\n * // Find direct connections for Alice\n * const aliceConnections = socialNetwork.getNeighbors(1);\n * console.log(aliceConnections[0].key); // 2;\n * console.log(aliceConnections[1].key); // 3;\n * console.log(aliceConnections.length); // 2;\n *\n * // Verify bidirectional connections\n * console.log(socialNetwork.hasEdge(1, 2)); // true;\n * console.log(socialNetwork.hasEdge(2, 1)); // true; // Friendship works both ways!\n *\n * // Remove a person from network\n * socialNetwork.deleteVertex(2); // Bob leaves\n * console.log(socialNetwork.hasVertex(2)); // false;\n * console.log(socialNetwork.size); // 4;\n *\n * // Alice loses Bob as a friend\n * const updatedAliceConnections = socialNetwork.getNeighbors(1);\n * console.log(updatedAliceConnections[0].key); // 3;\n * console.log(updatedAliceConnections[1]); // undefined;\n *\n * // Diana loses Bob as a friend\n * const dianaConnections = socialNetwork.getNeighbors(4);\n * console.log(dianaConnections[0].key); // 5;\n * console.log(dianaConnections[1]); // undefined;\n */\nexport class UndirectedGraph<\n V = any,\n E = any,\n VO extends UndirectedVertex<V> = UndirectedVertex<V>,\n EO extends UndirectedEdge<E> = UndirectedEdge<E>\n>\n extends AbstractGraph<V, E, VO, EO>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct an undirected graph with runtime defaults.\n * @param options - `GraphOptions<V>` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<GraphOptions<V>>) {\n super(options);\n this._edgeMap = new Map<VO, EO[]>();\n }\n\n protected _edgeMap: Map<VO, EO[]>;\n\n get edgeMap(): Map<VO, EO[]> {\n return this._edgeMap;\n }\n\n set edgeMap(v: Map<VO, EO[]>) {\n this._edgeMap = v;\n }\n\n /**\n * Construct an undirected graph from keys with value initializer `v => v`.\n * @template K - Vertex key type.\n * @param keys - Iterable of vertex keys.\n * @returns UndirectedGraph with all keys added.\n * @remarks Time O(V), Space O(V)\n */\n static fromKeys<K extends VertexKey>(\n keys: Iterable<K>\n ): UndirectedGraph<K, any, UndirectedVertex<K>, UndirectedEdge<any>> {\n const g: UndirectedGraph<K, any, UndirectedVertex<K>, UndirectedEdge<any>> = new UndirectedGraph<K, any>({\n vertexValueInitializer: (k: VertexKey) => k as K\n });\n for (const k of keys) g.addVertex(k);\n return g;\n }\n\n /**\n * Construct an undirected graph from `[key, value]` entries.\n * @template V - Vertex value type.\n * @param entries - Iterable of `[key, value]` pairs.\n * @returns UndirectedGraph with all vertices added.\n * @remarks Time O(V), Space O(V)\n */\n static fromEntries<V>(\n entries: Iterable<[VertexKey, V]>\n ): UndirectedGraph<V, any, UndirectedVertex<V>, UndirectedEdge<any>> {\n const g: UndirectedGraph<V, any, UndirectedVertex<V>, UndirectedEdge<any>> = new UndirectedGraph<V, any>();\n for (const [k, v] of entries) g.addVertex(k, v);\n return g;\n }\n\n /**\n * Create an undirected vertex instance. Does not insert into the graph.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n createVertex(key: VertexKey, value?: VO['value']): VO {\n return new UndirectedVertex(key, value) as VO;\n }\n\n /**\n * Create an undirected edge instance. Does not insert into the graph.\n * @param v1 - One endpoint key.\n * @param v2 - The other endpoint key.\n * @param weight - Edge weight; defaults to `defaultEdgeWeight`.\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n override createEdge(v1: VertexKey, v2: VertexKey, weight?: number, value?: EO['value']): EO {\n return new UndirectedEdge(v1, v2, weight ?? this.options.defaultEdgeWeight ?? 1, value) as EO;\n }\n\n /**\n * Get an undirected edge between two vertices, if present.\n * @param v1 - One vertex or key.\n * @param v2 - The other vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n getEdge(v1: VO | VertexKey | undefined, v2: VO | VertexKey | undefined): EO | undefined {\n let edgeMap: EO[] | undefined = [];\n\n if (v1 !== undefined && v2 !== undefined) {\n const vertex1: VO | undefined = this._getVertex(v1);\n const vertex2: VO | undefined = this._getVertex(v2);\n\n if (vertex1 && vertex2) {\n edgeMap = this._edgeMap.get(vertex1)?.filter(e => e.endpoints.includes(vertex2.key));\n }\n }\n\n return edgeMap ? edgeMap[0] || undefined : undefined;\n }\n\n /**\n * Delete a single undirected edge between two vertices.\n * @param v1 - One vertex or key.\n * @param v2 - The other vertex or key.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdgeBetween(v1: VO | VertexKey, v2: VO | VertexKey): EO | undefined {\n const vertex1: VO | undefined = this._getVertex(v1);\n const vertex2: VO | undefined = this._getVertex(v2);\n\n if (!vertex1 || !vertex2) {\n return undefined;\n }\n\n const v1Edges = this._edgeMap.get(vertex1);\n let removed: EO | undefined = undefined;\n if (v1Edges) {\n removed = arrayRemove<EO>(v1Edges, (e: EO) => e.endpoints.includes(vertex2.key))[0] || undefined;\n }\n const v2Edges = this._edgeMap.get(vertex2);\n if (v2Edges) {\n arrayRemove<EO>(v2Edges, (e: EO) => e.endpoints.includes(vertex1.key));\n }\n return removed;\n }\n\n /**\n * Delete an edge by instance or by a pair of keys.\n * @param edgeOrOneSideVertexKey - Edge instance or one endpoint vertex/key.\n * @param otherSideVertexKey - Required second endpoint when deleting by pair.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdge(edgeOrOneSideVertexKey: EO | VertexKey, otherSideVertexKey?: VertexKey): EO | undefined {\n let oneSide: VO | undefined, otherSide: VO | undefined;\n if (this.isVertexKey(edgeOrOneSideVertexKey)) {\n if (this.isVertexKey(otherSideVertexKey)) {\n oneSide = this._getVertex(edgeOrOneSideVertexKey);\n otherSide = this._getVertex(otherSideVertexKey);\n } else {\n return;\n }\n } else {\n oneSide = this._getVertex(edgeOrOneSideVertexKey.endpoints[0]);\n otherSide = this._getVertex(edgeOrOneSideVertexKey.endpoints[1]);\n }\n\n if (oneSide && otherSide) {\n return this.deleteEdgeBetween(oneSide, otherSide);\n } else {\n return;\n }\n }\n\n /**\n * Delete a vertex and remove it from all neighbor lists.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if removed; otherwise `false`.\n * @remarks Time O(deg), Space O(1)\n */\n deleteVertex(vertexOrKey: VO | VertexKey): boolean {\n let vertexKey: VertexKey;\n let vertex: VO | undefined;\n if (this.isVertexKey(vertexOrKey)) {\n vertex = this.getVertex(vertexOrKey);\n vertexKey = vertexOrKey;\n } else {\n vertex = vertexOrKey;\n vertexKey = this._getVertexKey(vertexOrKey);\n }\n\n /**\n * All neighbors connected via undirected edges.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg), Space O(deg)\n */\n const neighbors = this.getNeighbors(vertexOrKey);\n\n if (vertex) {\n neighbors.forEach(neighbor => {\n const neighborEdges = this._edgeMap.get(neighbor);\n if (neighborEdges) {\n const restEdges = neighborEdges.filter(edge => {\n return !edge.endpoints.includes(vertexKey);\n });\n this._edgeMap.set(neighbor, restEdges);\n }\n });\n this._edgeMap.delete(vertex);\n }\n\n return this._vertexMap.delete(vertexKey);\n }\n\n /**\n * Degree of a vertex (# of incident undirected edges).\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n degreeOf(vertexOrKey: VertexKey | VO): number {\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n return this._edgeMap.get(vertex)?.length || 0;\n } else {\n return 0;\n }\n }\n\n /**\n * Incident undirected edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg), Space O(deg)\n */\n edgesOf(vertexOrKey: VertexKey | VO): EO[] {\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n return this._edgeMap.get(vertex) || [];\n } else {\n return [];\n }\n }\n\n /**\n * Unique set of undirected edges across endpoints.\n * @returns Array of edges.\n * @remarks Time O(E), Space O(E)\n */\n edgeSet(): EO[] {\n const edgeSet: Set<EO> = new Set();\n this._edgeMap.forEach(edgeMap => {\n edgeMap.forEach(edge => {\n edgeSet.add(edge);\n });\n });\n return [...edgeSet];\n }\n\n getNeighbors(vertexOrKey: VO | VertexKey): VO[] {\n const neighbors: VO[] = [];\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n const neighborEdges = this.edgesOf(vertex);\n for (const edge of neighborEdges) {\n const neighbor = this._getVertex(edge.endpoints.filter(e => e !== vertex.key)[0]);\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n }\n return neighbors;\n }\n\n /**\n * Resolve an edge's two endpoints to vertex instances.\n * @param edge - Edge instance.\n * @returns `[v1, v2]` or `undefined` if either endpoint is missing.\n * @remarks Time O(1), Space O(1)\n */\n getEndsOfEdge(edge: EO): [VO, VO] | undefined {\n if (!this.hasEdge(edge.endpoints[0], edge.endpoints[1])) {\n return undefined;\n }\n const v1 = this._getVertex(edge.endpoints[0]);\n const v2 = this._getVertex(edge.endpoints[1]);\n if (v1 && v2) {\n return [v1, v2];\n } else {\n return undefined;\n }\n }\n\n /**\n * Whether the graph has no vertices and no edges.\n * @remarks Time O(1), Space O(1)\n */\n isEmpty(): boolean {\n return this.vertexMap.size === 0 && this.edgeMap.size === 0;\n }\n\n /**\n * Remove all vertices and edges.\n * @remarks Time O(V + E), Space O(1)\n */\n clear() {\n this._vertexMap = new Map<VertexKey, VO>();\n this._edgeMap = new Map<VO, EO[]>();\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Tarjan-based bridge and articulation point detection.\n * @returns `{ dfnMap, lowMap, bridges, cutVertices }`.\n * @remarks Time O(V + E), Space O(V + E)\n */\n tarjan(): { dfnMap: Map<VO, number>; lowMap: Map<VO, number>; bridges: EO[]; cutVertices: VO[] } {\n const dfnMap = new Map<VO, number>();\n const lowMap = new Map<VO, number>();\n const bridges: EO[] = [];\n const cutVertices: VO[] = [];\n\n let time = 0;\n\n const dfs = (vertex: VO, parent: VO | undefined) => {\n dfnMap.set(vertex, time);\n lowMap.set(vertex, time);\n time++;\n\n const neighbors = this.getNeighbors(vertex);\n let childCount = 0;\n\n for (const neighbor of neighbors) {\n if (!dfnMap.has(neighbor)) {\n childCount++;\n dfs(neighbor, vertex);\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, lowMap.get(neighbor)!));\n\n if (lowMap.get(neighbor)! > dfnMap.get(vertex)!) {\n // Found a bridge\n const edge = this.getEdge(vertex, neighbor);\n if (edge) {\n bridges.push(edge);\n }\n }\n\n if (parent !== undefined && lowMap.get(neighbor)! >= dfnMap.get(vertex)!) {\n // Found an articulation point\n cutVertices.push(vertex);\n }\n } else if (neighbor !== parent) {\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, dfnMap.get(neighbor)!));\n }\n }\n\n if (parent === undefined && childCount > 1) {\n // Special case for root in DFS tree\n cutVertices.push(vertex);\n }\n };\n\n for (const vertex of this.vertexMap.values()) {\n if (!dfnMap.has(vertex)) {\n dfs(vertex, undefined);\n }\n }\n\n return {\n dfnMap,\n lowMap,\n bridges,\n cutVertices\n };\n }\n\n /**\n * Get bridges discovered by `tarjan()`.\n * @returns Array of edges that are bridges.\n * @remarks Time O(B), Space O(1)\n */\n getBridges() {\n return this.tarjan().bridges;\n }\n\n /**\n * Get articulation points discovered by `tarjan()`.\n * @returns Array of cut vertices.\n * @remarks Time O(C), Space O(1)\n */\n getCutVertices() {\n return this.tarjan().cutVertices;\n }\n\n /**\n * DFN index map computed by `tarjan()`.\n * @returns Map from vertex to DFN index.\n * @remarks Time O(V), Space O(V)\n */\n getDFNMap() {\n return this.tarjan().dfnMap;\n }\n\n /**\n * LOW link map computed by `tarjan()`.\n * @returns Map from vertex to LOW value.\n * @remarks Time O(V), Space O(V)\n */\n getLowMap() {\n return this.tarjan().lowMap;\n }\n\n /**\n * Internal hook to attach an undirected edge into adjacency maps.\n * @param edge - Edge instance.\n * @returns `true` if both endpoints exist; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addEdge(edge: EO): boolean {\n for (const end of edge.endpoints) {\n const endVertex = this._getVertex(end);\n if (endVertex === undefined) return false;\n if (endVertex) {\n const edgeMap = this._edgeMap.get(endVertex);\n if (edgeMap) {\n edgeMap.push(edge);\n } else {\n this._edgeMap.set(endVertex, [edge]);\n }\n }\n }\n return true;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { MapGraphCoordinate, VertexKey } from '../../types';\nimport { DirectedEdge, DirectedGraph, DirectedVertex } from './directed-graph';\n\nexport class MapVertex<V = any> extends DirectedVertex<V> {\n lat: number;\n long: number;\n\n constructor(key: VertexKey, value: V, lat: number, long: number) {\n super(key, value);\n this.lat = lat;\n this.long = long;\n }\n}\n\nexport class MapEdge<E = any> extends DirectedEdge<E> {\n constructor(src: VertexKey, dest: VertexKey, weight?: number, value?: E) {\n super(src, dest, weight, value);\n }\n}\n\n/**\n * Directed graph variant carrying geospatial coordinates.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (MapVertex<V>).\n * @template EO - Concrete edge class (MapEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example examples will be generated by unit test\n */\nexport class MapGraph<\n V = any,\n E = any,\n VO extends MapVertex<V> = MapVertex<V>,\n EO extends MapEdge<E> = MapEdge<E>\n> extends DirectedGraph<V, E, VO, EO> {\n /**\n * Construct a MapGraph.\n * @param originCoord - Origin coordinate `[lat, long]` used as default.\n * @param bottomRight - Optional bottom-right coordinate for bounding boxes.\n * @remarks Time O(1), Space O(1)\n */\n constructor(originCoord: MapGraphCoordinate, bottomRight?: MapGraphCoordinate) {\n super();\n this._originCoord = originCoord;\n this._bottomRight = bottomRight;\n }\n\n protected _originCoord: MapGraphCoordinate = [0, 0];\n\n get originCoord(): MapGraphCoordinate {\n return this._originCoord;\n }\n\n protected _bottomRight: MapGraphCoordinate | undefined;\n\n get bottomRight(): MapGraphCoordinate | undefined {\n return this._bottomRight;\n }\n\n /**\n * Create a map vertex with optional coordinates.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @param lat - Latitude (defaults to `originCoord[0]`).\n * @param long - Longitude (defaults to `originCoord[1]`).\n * @returns MapVertex instance.\n * @remarks Time O(1), Space O(1)\n */\n override createVertex(\n key: VertexKey,\n value?: V,\n lat: number = this.originCoord[0],\n long: number = this.originCoord[1]\n ): VO {\n return new MapVertex(key, value, lat, long) as VO;\n }\n\n /**\n * Create a map edge (directed) with optional weight/value.\n * @param src - Source key.\n * @param dest - Destination key.\n * @param weight - Edge weight.\n * @param value - Edge payload.\n * @returns MapEdge instance.\n * @remarks Time O(1), Space O(1)\n */\n override createEdge(src: VertexKey, dest: VertexKey, weight?: number, value?: E): EO {\n return new MapEdge(src, dest, weight, value) as EO;\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Include `originCoord` and `bottomRight` so `clone()/filter()` preserve geospatial settings.\n * @returns Options bag extending super snapshot.\n * @remarks Time O(1), Space O(1)\n */\n protected override _snapshotOptions(): Record<string, unknown> {\n return { ...(super._snapshotOptions() as any), originCoord: this.originCoord, bottomRight: this.bottomRight };\n }\n\n /**\n * Re-create a same-species MapGraph instance from snapshot options.\n * @param options - Snapshot options providing `originCoord`/`bottomRight`.\n * @returns Empty MapGraph instance of `this` type.\n * @remarks Time O(1), Space O(1)\n */\n protected override _createInstance(options?: Partial<Record<string, unknown>>): this {\n const { originCoord, bottomRight } = (options || {}) as {\n originCoord?: [number, number];\n bottomRight?: [number, number] | undefined;\n };\n const oc = (originCoord ?? this.originCoord) as [number, number];\n const br = (bottomRight ?? this.bottomRight) as [number, number] | undefined;\n return new MapGraph<V, E, VO, EO>(oc, br) as this;\n }\n}\n","export enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n // if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n // if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n BinaryTreeOptions,\n BinaryTreePrintOptions,\n BTNEntry,\n DFSOrderPattern,\n DFSStackItem,\n EntryCallback,\n FamilyPosition,\n IterationType,\n NodeCallback,\n NodeDisplayLayout,\n NodePredicate,\n OptNodeOrNull,\n RBTNColor,\n ToEntryFn,\n Trampoline\n} from '../../types';\nimport { IBinaryTree } from '../../interfaces';\nimport { isComparable, makeTrampoline, makeTrampolineThunk } from '../../utils';\nimport { Queue } from '../queue';\nimport { IterableEntryBase } from '../base';\nimport { DFSOperation, Range } from '../../common';\n\n/**\n * @template K - The type of the key.\n * @template V - The type of the value.\n */\nexport class BinaryTreeNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: BinaryTreeNode<K, V> = undefined;\n\n /**\n * Creates an instance of BinaryTreeNode.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key of the node.\n * @param [value] - The value associated with the key.\n */\n constructor(key: K, value?: V) {\n this.key = key;\n this.value = value;\n }\n\n _left?: BinaryTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the left child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The left child.\n */\n get left(): BinaryTreeNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Sets the left child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the left child.\n */\n set left(v: BinaryTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this as unknown as BinaryTreeNode<K, V>;\n }\n this._left = v;\n }\n\n _right?: BinaryTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the right child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The right child.\n */\n get right(): BinaryTreeNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Sets the right child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the right child.\n */\n set right(v: BinaryTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * A general Binary Tree implementation.\n *\n * @remarks\n * This class implements a basic Binary Tree, not a Binary Search Tree.\n * The `add` operation inserts nodes level-by-level (BFS) into the first available slot.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n * @template R - The type of the raw data object (if using `toEntryFn`).\n * 1. Two Children Maximum: Each node has at most two children.\n * 2. Left and Right Children: Nodes have distinct left and right children.\n * 3. Depth and Height: Depth is the number of edges from the root to a node; height is the maximum depth in the tree.\n * 4. Subtrees: Each child of a node forms the root of a subtree.\n * 5. Leaf Nodes: Nodes without children are leaves.\n *\n * @example\n * // basic BinaryTree creation and insertion\n * // Create a BinaryTree with entries\n * const entries: [number, string][] = [\n * [6, 'six'],\n * [1, 'one'],\n * [2, 'two'],\n * [7, 'seven'],\n * [5, 'five'],\n * [3, 'three'],\n * [4, 'four'],\n * [9, 'nine'],\n * [8, 'eight']\n * ];\n *\n * const tree = new BinaryTree(entries);\n *\n * // Verify size\n * console.log(tree.size); // 9;\n *\n * // Add new element\n * tree.add(10, 'ten');\n * console.log(tree.size); // 10;\n * @example\n * // BinaryTree get and has operations\n * const tree = new BinaryTree(\n * [\n * [5, 'five'],\n * [3, 'three'],\n * [7, 'seven'],\n * [1, 'one'],\n * [4, 'four'],\n * [6, 'six'],\n * [8, 'eight']\n * ],\n * { isMapMode: false }\n * );\n *\n * // Check if key exists\n * console.log(tree.has(5)); // true;\n * console.log(tree.has(10)); // false;\n *\n * // Get value by key\n * console.log(tree.get(3)); // 'three';\n * console.log(tree.get(7)); // 'seven';\n * console.log(tree.get(100)); // undefined;\n *\n * // Get node structure\n * const node = tree.getNode(5);\n * console.log(node?.key); // 5;\n * console.log(node?.value); // 'five';\n * @example\n * // BinaryTree level-order traversal\n * const tree = new BinaryTree([\n * [1, 'one'],\n * [2, 'two'],\n * [3, 'three'],\n * [4, 'four'],\n * [5, 'five'],\n * [6, 'six'],\n * [7, 'seven']\n * ]);\n *\n * // Binary tree maintains level-order insertion\n * // Complete binary tree structure\n * console.log(tree.size); // 7;\n *\n * // Verify all keys are present\n * console.log(tree.has(1)); // true;\n * console.log(tree.has(4)); // true;\n * console.log(tree.has(7)); // true;\n *\n * // Iterate through tree\n * const keys: number[] = [];\n * for (const [key] of tree) {\n * keys.push(key);\n * }\n * console.log(keys.length); // 7;\n * @example\n * // determine loan approval using a decision tree\n * // Decision tree structure\n * const loanDecisionTree = new BinaryTree<string>(\n * ['stableIncome', 'goodCredit', 'Rejected', 'Approved', 'Rejected'],\n * { isDuplicate: true }\n * );\n *\n * function determineLoanApproval(\n * node?: BinaryTreeNode<string> | null,\n * conditions?: { [key: string]: boolean }\n * ): string {\n * if (!node) throw new Error('Invalid node');\n *\n * // If it's a leaf node, return the decision result\n * if (!node.left && !node.right) return node.key;\n *\n * // Check if a valid condition exists for the current node's key\n * return conditions?.[node.key]\n * ? determineLoanApproval(node.left, conditions)\n * : determineLoanApproval(node.right, conditions);\n * }\n *\n * // Test case 1: Stable income and good credit score\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: true, goodCredit: true })); // 'Approved';\n *\n * // Test case 2: Stable income but poor credit score\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: true, goodCredit: false })); // 'Rejected';\n *\n * // Test case 3: No stable income\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: false, goodCredit: true })); // 'Rejected';\n *\n * // Test case 4: No stable income and poor credit score\n * console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: false, goodCredit: false })); // 'Rejected';\n * @example\n * // evaluate the arithmetic expression represented by the binary tree\n * const expressionTree = new BinaryTree<number | string>(['+', 3, '*', null, null, 5, '-', null, null, 2, 8]);\n *\n * function evaluate(node?: BinaryTreeNode<number | string> | null): number {\n * if (!node) return 0;\n *\n * if (typeof node.key === 'number') return node.key;\n *\n * const leftValue = evaluate(node.left); // Evaluate the left subtree\n * const rightValue = evaluate(node.right); // Evaluate the right subtree\n *\n * // Perform the operation based on the current node's operator\n * switch (node.key) {\n * case '+':\n * return leftValue + rightValue;\n * case '-':\n * return leftValue - rightValue;\n * case '*':\n * return leftValue * rightValue;\n * case '/':\n * return rightValue !== 0 ? leftValue / rightValue : 0; // Handle division by zero\n * default:\n * throw new Error(`Unsupported operator: ${node.key}`);\n * }\n * }\n *\n * console.log(evaluate(expressionTree.root)); // -27;\n */\nexport class BinaryTree<K = any, V = any, R = any>\n extends IterableEntryBase<K, V | undefined>\n implements IBinaryTree<K, V, R>\n{\n iterationType: IterationType = 'ITERATIVE';\n\n /**\n * Creates an instance of BinaryTree.\n * @remarks Time O(N * M), where N is the number of items in `keysNodesEntriesOrRaws` and M is the tree size at insertion time (due to O(M) `add` operation). Space O(N) for storing the nodes.\n *\n * @param [keysNodesEntriesOrRaws=[]] - An iterable of items to add.\n * @param [options] - Configuration options for the tree.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: BinaryTreeOptions<K, V, R>\n ) {\n super();\n if (options) {\n const { iterationType, toEntryFn, isMapMode, isDuplicate } = options;\n if (iterationType) this.iterationType = iterationType;\n if (isMapMode !== undefined) this._isMapMode = isMapMode;\n if (isDuplicate !== undefined) this._isDuplicate = isDuplicate;\n if (typeof toEntryFn === 'function') this._toEntryFn = toEntryFn;\n else if (toEntryFn) throw TypeError('toEntryFn must be a function type');\n }\n\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected _isMapMode = true;\n\n /**\n * Gets whether the tree is in Map mode.\n * @remarks In Map mode (default), values are stored in an external Map, and nodes only hold keys. If false, values are stored directly on the nodes. Time O(1)\n *\n * @returns True if in Map mode, false otherwise.\n */\n get isMapMode() {\n return this._isMapMode;\n }\n\n protected _isDuplicate = false;\n\n /**\n * Gets whether the tree allows duplicate keys.\n * @remarks Time O(1)\n *\n * @returns True if duplicates are allowed, false otherwise.\n */\n get isDuplicate() {\n return this._isDuplicate;\n }\n\n protected _store = new Map<K, V | undefined>();\n\n /**\n * Gets the external value store (used in Map mode).\n * @remarks Time O(1)\n *\n * @returns The map storing key-value pairs.\n */\n get store() {\n return this._store;\n }\n\n protected _root?: BinaryTreeNode<K, V> | null | undefined;\n\n /**\n * Gets the root node of the tree.\n * @remarks Time O(1)\n *\n * @returns The root node.\n */\n get root(): BinaryTreeNode<K, V> | null | undefined {\n return this._root;\n }\n\n protected _size: number = 0;\n\n /**\n * Gets the number of nodes in the tree.\n * @remarks Time O(1)\n *\n * @returns The size of the tree.\n */\n get size(): number {\n return this._size;\n }\n\n protected _NIL: BinaryTreeNode<K, V> = new BinaryTreeNode<K, V>(NaN as K) as unknown as BinaryTreeNode<K, V>;\n\n /**\n * Gets the sentinel NIL node (used in self-balancing trees like Red-Black Tree).\n * @remarks Time O(1)\n *\n * @returns The NIL node.\n */\n get NIL(): BinaryTreeNode<K, V> {\n return this._NIL;\n }\n\n protected _toEntryFn?: ToEntryFn<K, V, R>;\n\n /**\n * Gets the function used to convert raw data objects (R) into [key, value] entries.\n * @remarks Time O(1)\n *\n * @returns The conversion function.\n */\n get toEntryFn() {\n return this._toEntryFn;\n }\n\n /**\n * (Protected) Creates a new node.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key for the new node.\n * @param [value] - The value for the new node (used if not in Map mode).\n * @returns The newly created node.\n */\n createNode(key: K, value?: V): BinaryTreeNode<K, V> {\n return new BinaryTreeNode<K, V>(key, this._isMapMode ? undefined : value);\n }\n\n /**\n * Creates a new, empty tree of the same type and configuration.\n * @remarks Time O(1) (excluding options cloning), Space O(1)\n *\n * @param [options] - Optional overrides for the new tree's options.\n * @returns A new, empty tree instance.\n */\n createTree(options?: Partial<BinaryTreeOptions<K, V, R>>): this {\n return this._createInstance<K, V, R>(options);\n }\n\n /**\n * Ensures the input is a node. If it's a key or entry, it searches for the node.\n * @remarks Time O(1) if a node is passed. O(N) if a key or entry is passed (due to `getNode` performing a full search). Space O(1) if iterative search, O(H) if recursive (where H is height, O(N) worst-case).\n *\n * @param keyNodeOrEntry - The item to resolve to a node.\n * @param [iterationType=this.iterationType] - The traversal method to use if searching.\n * @returns The resolved node, or null/undefined if not found or input is null/undefined.\n */\n ensureNode(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType: IterationType = this.iterationType\n ): BinaryTreeNode<K, V> | null | undefined {\n if (keyNodeOrEntry === null) return null;\n if (keyNodeOrEntry === undefined) return;\n if (keyNodeOrEntry === this._NIL) return;\n\n if (this.isNode(keyNodeOrEntry)) return keyNodeOrEntry;\n\n if (this.isEntry(keyNodeOrEntry)) {\n const key = keyNodeOrEntry[0];\n if (key === null) return null;\n if (key === undefined) return;\n return this.getNode(key, this._root, iterationType);\n }\n\n return this.getNode(keyNodeOrEntry, this._root, iterationType);\n }\n\n /**\n * Checks if the given item is a `BinaryTreeNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a node, false otherwise.\n */\n isNode(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BinaryTreeNode<K, V> {\n return keyNodeOrEntry instanceof BinaryTreeNode;\n }\n\n /**\n * Checks if the given item is a raw data object (R) that needs conversion via `toEntryFn`.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeEntryOrRaw - The item to check.\n * @returns True if it's a raw object, false otherwise.\n */\n isRaw(\n keyNodeEntryOrRaw: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n ): keyNodeEntryOrRaw is R {\n return this._toEntryFn !== undefined && typeof keyNodeEntryOrRaw === 'object';\n }\n\n /**\n * Checks if the given item is a \"real\" node (i.e., not null, undefined, or NIL).\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a real node, false otherwise.\n */\n isRealNode(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BinaryTreeNode<K, V> {\n if (keyNodeOrEntry === this._NIL || keyNodeOrEntry === null || keyNodeOrEntry === undefined) return false;\n return this.isNode(keyNodeOrEntry);\n }\n\n /**\n * Checks if the given item is either a \"real\" node or null.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a real node or null, false otherwise.\n */\n isRealNodeOrNull(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BinaryTreeNode<K, V> | null {\n return keyNodeOrEntry === null || this.isRealNode(keyNodeOrEntry);\n }\n\n /**\n * Checks if the given item is the sentinel NIL node.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's the NIL node, false otherwise.\n */\n isNIL(keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined): boolean {\n return keyNodeOrEntry === this._NIL;\n }\n\n /**\n * Checks if the given item is a `Range` object.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeEntryOrPredicate - The item to check.\n * @returns True if it's a Range, false otherwise.\n */\n isRange(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>\n | Range<K>\n ): keyNodeEntryOrPredicate is Range<K> {\n return keyNodeEntryOrPredicate instanceof Range;\n }\n\n /**\n * Checks if a node is a leaf (has no real children).\n * @remarks Time O(N) if a key/entry is passed (due to `ensureNode`). O(1) if a node is passed. Space O(1) or O(H) (from `ensureNode`).\n *\n * @param keyNodeOrEntry - The node to check.\n * @returns True if the node is a leaf, false otherwise.\n */\n isLeaf(keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined): boolean {\n keyNodeOrEntry = this.ensureNode(keyNodeOrEntry);\n if (keyNodeOrEntry === undefined) return false;\n if (keyNodeOrEntry === null) return true; // A null spot is considered a leaf\n return !this.isRealNode(keyNodeOrEntry.left) && !this.isRealNode(keyNodeOrEntry.right);\n }\n\n /**\n * Checks if the given item is a [key, value] entry pair.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's an entry, false otherwise.\n */\n isEntry(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BTNEntry<K, V> {\n return Array.isArray(keyNodeOrEntry) && keyNodeOrEntry.length === 2;\n }\n\n /**\n * Checks if the given key is valid (comparable or null).\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key to validate.\n * @returns True if the key is valid, false otherwise.\n */\n isValidKey(key: any): key is K {\n if (key === null) return true;\n return isComparable(key);\n }\n\n /**\n * Adds a new node to the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).\n *\n * @param keyNodeOrEntry - The key, node, or entry to add.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n add(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (newNode === undefined) return false;\n\n if (!this._root) {\n this._setRoot(newNode);\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size = 1;\n return true;\n }\n\n const queue = new Queue<BinaryTreeNode<K, V>>([this._root]);\n let potentialParent: BinaryTreeNode<K, V> | undefined;\n while (queue.length > 0) {\n const cur = queue.shift();\n\n if (!cur) continue;\n\n if (!this._isDuplicate) {\n if (newNode !== null && cur.key === newNode.key) {\n this._replaceNode(cur, newNode);\n if (this._isMapMode) this._setValue(cur.key, newValue);\n return true; // Replaced existing node\n }\n }\n\n if (potentialParent === undefined && (cur.left === undefined || cur.right === undefined)) {\n potentialParent = cur;\n }\n\n if (cur.left !== null) {\n if (cur.left) queue.push(cur.left);\n }\n if (cur.right !== null) {\n if (cur.right) queue.push(cur.right);\n }\n }\n\n if (potentialParent) {\n if (potentialParent.left === undefined) {\n potentialParent.left = newNode;\n } else if (potentialParent.right === undefined) {\n potentialParent.right = newNode;\n }\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n\n return false; // Should not happen if tree is not full?\n }\n\n /**\n * Adds or updates a new node to the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).\n *\n * @param keyNodeOrEntry - The key, node, or entry to add or update.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n set(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n return this.add(keyNodeOrEntry, value);\n }\n\n /**\n * Adds multiple items to the tree.\n * @remarks Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) `add` operation). Space O(M) (from `add`) + O(N) (for the `inserted` array).\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add.\n * @param [values] - An optional parallel iterable of values.\n * @returns An array of booleans indicating the success of each individual `add` operation.\n */\n addMany(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n >,\n values?: Iterable<V | undefined>\n ): boolean[] {\n const inserted: boolean[] = [];\n\n let valuesIterator: Iterator<V | undefined> | undefined;\n if (values) {\n valuesIterator = values[Symbol.iterator]();\n }\n\n for (let keyNodeEntryOrRaw of keysNodesEntriesOrRaws) {\n let value: V | undefined | null = undefined;\n\n if (valuesIterator) {\n const valueResult = valuesIterator.next();\n if (!valueResult.done) {\n value = valueResult.value;\n }\n }\n if (this.isRaw(keyNodeEntryOrRaw)) keyNodeEntryOrRaw = this._toEntryFn!(keyNodeEntryOrRaw);\n inserted.push(this.add(keyNodeEntryOrRaw, value));\n }\n\n return inserted;\n }\n\n /**\n * Adds or updates multiple items to the tree.\n * @remarks Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) `add` operation). Space O(M) (from `add`) + O(N) (for the `inserted` array).\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add or update.\n * @param [values] - An optional parallel iterable of values.\n * @returns An array of booleans indicating the success of each individual `add` operation.\n */\n setMany(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n >,\n values?: Iterable<V | undefined>\n ): boolean[] {\n return this.addMany(keysNodesEntriesOrRaws, values);\n }\n\n /**\n * Merges another tree into this one by adding all its nodes.\n * @remarks Time O(N * M), same as `addMany`, where N is the size of `anotherTree` and M is the size of this tree. Space O(M) (from `add`).\n *\n * @param anotherTree - The tree to merge.\n */\n merge(anotherTree: BinaryTree<K, V, R>) {\n this.addMany(anotherTree, []);\n }\n\n /**\n * Clears the tree and refills it with new items.\n * @remarks Time O(N) (for `clear`) + O(N * M) (for `addMany`) = O(N * M). Space O(M) (from `addMany`).\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add.\n * @param [values] - An optional parallel iterable of values.\n */\n refill(\n keysNodesEntriesOrRaws: Iterable<\n K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n >,\n values?: Iterable<V | undefined>\n ): void {\n this.clear();\n this.addMany(keysNodesEntriesOrRaws, values);\n }\n\n /**\n * Deletes a node from the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation finds the node, and if it has two children, swaps it with the rightmost node of its left subtree (in-order predecessor) before deleting. Time O(N) in the worst case. O(N) to find the node (`getNode`) and O(H) (which is O(N) worst-case) to find the rightmost node. Space O(1) (if `getNode` is iterative, which it is).\n *\n * @param keyNodeOrEntry - The node to delete.\n * @returns An array containing deletion results (for compatibility with self-balancing trees).\n */\n delete(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[] {\n const deletedResult: BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[] = [];\n if (!this._root) return deletedResult;\n\n const curr = this.getNode(keyNodeOrEntry);\n if (!curr) return deletedResult;\n\n const parent: BinaryTreeNode<K, V> | undefined = curr?.parent;\n let needBalanced: BinaryTreeNode<K, V> | undefined;\n let orgCurrent: BinaryTreeNode<K, V> | undefined = curr;\n\n if (!curr.left && !curr.right && !parent) {\n // Deleting the root with no children\n this._setRoot(undefined);\n } else if (curr.left) {\n // Node has a left child (or two children)\n // Find the rightmost node in the left subtree\n const leftSubTreeRightMost = this.getRightMost(node => node, curr.left);\n if (leftSubTreeRightMost) {\n const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;\n // Swap properties\n orgCurrent = this._swapProperties(curr, leftSubTreeRightMost);\n // `orgCurrent` is now the node to be physically deleted (which was the rightmost)\n if (parentOfLeftSubTreeMax) {\n // Unlink the rightmost node\n if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost)\n parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;\n else parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;\n needBalanced = parentOfLeftSubTreeMax;\n }\n }\n } else if (parent) {\n // Node has no left child, but has a parent\n // Promote the right child (which could be null)\n const { familyPosition: fp } = curr;\n if (fp === 'LEFT' || fp === 'ROOT_LEFT') {\n parent.left = curr.right;\n } else if (fp === 'RIGHT' || fp === 'ROOT_RIGHT') {\n parent.right = curr.right;\n }\n needBalanced = parent;\n } else {\n // Deleting the root, which has no left child\n // Promote the right child as the new root\n this._setRoot(curr.right);\n curr.right = undefined;\n }\n\n this._size = this._size - 1;\n\n deletedResult.push({ deleted: orgCurrent, needBalanced });\n if (this._isMapMode && orgCurrent) this._store.delete(orgCurrent.key);\n return deletedResult;\n }\n\n search(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne?: boolean\n ): (K | undefined)[];\n\n search<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne: boolean,\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Searches the tree for nodes matching a predicate.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Performs a full DFS (pre-order) scan of the tree. Time O(N), as it may visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).\n *\n * @template C - The type of the callback function.\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [onlyOne=false] - If true, stops after finding the first match.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on matching nodes.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - Whether to use 'RECURSIVE' or 'ITERATIVE' search.\n * @returns An array of results from the callback function for each matching node.\n */\n search<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne = false,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n if (keyNodeEntryOrPredicate === undefined) return [];\n if (keyNodeEntryOrPredicate === null) return [];\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n const predicate = this._ensurePredicate(keyNodeEntryOrPredicate);\n\n const ans: ReturnType<C>[] = [];\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V>) => {\n if (predicate(cur)) {\n ans.push(callback(cur));\n if (onlyOne) return;\n }\n if (!this.isRealNode(cur.left) && !this.isRealNode(cur.right)) return;\n if (this.isRealNode(cur.left)) dfs(cur.left);\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(startNode);\n } else {\n const stack = [startNode];\n\n while (stack.length > 0) {\n const cur = stack.pop();\n if (this.isRealNode(cur)) {\n if (predicate(cur)) {\n ans.push(callback(cur));\n if (onlyOne) return ans;\n }\n if (this.isRealNode(cur.left)) stack.push(cur.left);\n if (this.isRealNode(cur.right)) stack.push(cur.right);\n }\n }\n }\n\n return ans;\n }\n\n /**\n * Gets all nodes matching a predicate.\n * @remarks Time O(N) (via `search`). Space O(H) or O(N) (via `search`).\n *\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [onlyOne=false] - If true, stops after finding the first match.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of matching nodes.\n */\n getNodes(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): BinaryTreeNode<K, V>[];\n\n getNodes(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n onlyOne = false,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): (BinaryTreeNode<K, V> | null)[] {\n return this.search(keyNodeEntryOrPredicate, onlyOne, node => node, startNode, iterationType);\n }\n\n /**\n * Gets the first node matching a predicate.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via `search`). Space O(H) or O(N) (via `search`).\n *\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The first matching node, or undefined if not found.\n */\n getNode(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): BinaryTreeNode<K, V> | null | undefined {\n return this.search(keyNodeEntryOrPredicate, true, node => node, startNode, iterationType)[0];\n }\n\n /**\n * Gets the value associated with a key.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(1) if in Map mode. O(N) if not in Map mode (uses `getNode`). Space O(1) if in Map mode. O(H) or O(N) otherwise.\n *\n * @param keyNodeEntryOrPredicate - The key, node, or entry to get the value for.\n * @param [startNode=this._root] - The node to start searching from (if not in Map mode).\n * @param [iterationType=this.iterationType] - The traversal method (if not in Map mode).\n * @returns The associated value, or undefined.\n */\n override get(\n keyNodeEntryOrPredicate: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): V | undefined {\n if (this._isMapMode) {\n const key = this._extractKey(keyNodeEntryOrPredicate);\n if (key === null || key === undefined) return;\n return this._store.get(key);\n }\n return this.getNode(keyNodeEntryOrPredicate, startNode, iterationType)?.value;\n }\n\n /**\n * Checks if a node matching the predicate exists in the tree.\n * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via `search`). Space O(H) or O(N) (via `search`).\n *\n * @param [keyNodeEntryOrPredicate] - The key, node, entry, or predicate to check for.\n * @param [startNode] - The node to start the search from.\n * @param [iterationType] - The traversal method.\n * @returns True if a matching node exists, false otherwise.\n */\n override has(\n keyNodeEntryOrPredicate?:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): boolean;\n\n override has(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): boolean {\n return this.search(keyNodeEntryOrPredicate, true, node => node, startNode, iterationType).length > 0;\n }\n\n /**\n * Clears the tree of all nodes and values.\n * @remarks Time O(N) if in Map mode (due to `_store.clear()`), O(1) otherwise. Space O(1)\n */\n clear() {\n this._clearNodes();\n if (this._isMapMode) this._clearValues();\n }\n\n /**\n * Checks if the tree is empty.\n * @remarks Time O(1), Space O(1)\n *\n * @returns True if the tree has no nodes, false otherwise.\n */\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Checks if the tree is perfectly balanced.\n * @remarks A tree is perfectly balanced if the difference between min and max height is at most 1. Time O(N), as it requires two full traversals (`getMinHeight` and `getHeight`). Space O(H) or O(N) (from height calculation).\n *\n * @param [startNode=this._root] - The node to start checking from.\n * @returns True if perfectly balanced, false otherwise.\n */\n isPerfectlyBalanced(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ): boolean {\n return this.getMinHeight(startNode) + 1 >= this.getHeight(startNode);\n }\n\n /**\n * Checks if the tree is a valid Binary Search Tree (BST).\n * @remarks Time O(N), as it must visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).\n *\n * @param [startNode=this._root] - The node to start checking from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns True if it's a valid BST, false otherwise.\n */\n isBST(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): boolean {\n const startNodeSired = this.ensureNode(startNode);\n if (!startNodeSired) return true;\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V> | null | undefined, min: number, max: number): boolean => {\n if (!this.isRealNode(cur)) return true;\n const numKey = Number(cur.key);\n if (numKey <= min || numKey >= max) return false;\n return dfs(cur.left, min, numKey) && dfs(cur.right, numKey, max);\n };\n\n const isStandardBST = dfs(startNodeSired, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);\n const isInverseBST = dfs(startNodeSired, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER); // Check for reverse BST\n return isStandardBST || isInverseBST;\n } else {\n // Iterative in-order traversal check\n const checkBST = (checkMax = false) => {\n const stack: BinaryTreeNode<K, V>[] = [];\n let prev = checkMax ? Number.MAX_SAFE_INTEGER : Number.MIN_SAFE_INTEGER;\n let curr: BinaryTreeNode<K, V> | null | undefined = startNodeSired;\n while (this.isRealNode(curr) || stack.length > 0) {\n while (this.isRealNode(curr)) {\n stack.push(curr);\n curr = curr.left;\n }\n curr = stack.pop()!;\n const numKey = Number(curr.key);\n if (!this.isRealNode(curr) || (!checkMax && prev >= numKey) || (checkMax && prev <= numKey)) return false;\n prev = numKey;\n curr = curr.right;\n }\n return true;\n };\n const isStandardBST = checkBST(false);\n const isInverseBST = checkBST(true);\n return isStandardBST || isInverseBST;\n }\n }\n\n /**\n * Gets the depth of a node (distance from `startNode`).\n * @remarks Time O(H), where H is the depth of the `dist` node relative to `startNode`. O(N) worst-case. Space O(1).\n *\n * @param dist - The node to find the depth of.\n * @param [startNode=this._root] - The node to measure depth from (defaults to root).\n * @returns The depth (0 if `dist` is `startNode`).\n */\n getDepth(\n dist: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ): number {\n let distEnsured = this.ensureNode(dist);\n const beginRootEnsured = this.ensureNode(startNode);\n let depth = 0;\n while (distEnsured?.parent) {\n if (distEnsured === beginRootEnsured) {\n return depth;\n }\n depth++;\n distEnsured = distEnsured.parent;\n }\n return depth;\n }\n\n /**\n * Gets the maximum height of the tree (longest path from startNode to a leaf).\n * @remarks Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative stack (storing node + depth).\n *\n * @param [startNode=this._root] - The node to start measuring from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The height ( -1 for an empty tree, 0 for a single-node tree).\n */\n getHeight(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): number {\n startNode = this.ensureNode(startNode);\n if (!this.isRealNode(startNode)) return -1;\n\n if (iterationType === 'RECURSIVE') {\n const _getMaxHeight = (cur: BinaryTreeNode<K, V> | null | undefined): number => {\n if (!this.isRealNode(cur)) return -1;\n const leftHeight = _getMaxHeight(cur.left);\n const rightHeight = _getMaxHeight(cur.right);\n return Math.max(leftHeight, rightHeight) + 1;\n };\n\n return _getMaxHeight(startNode);\n } else {\n // Iterative (using DFS)\n const stack: { node: BinaryTreeNode<K, V>; depth: number }[] = [{ node: startNode, depth: 0 }];\n let maxHeight = 0;\n\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n\n if (this.isRealNode(node.left)) stack.push({ node: node.left, depth: depth + 1 });\n if (this.isRealNode(node.right)) stack.push({ node: node.right, depth: depth + 1 });\n\n maxHeight = Math.max(maxHeight, depth);\n }\n\n return maxHeight;\n }\n }\n\n /**\n * Gets the minimum height of the tree (shortest path from startNode to a leaf).\n * @remarks Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative (due to `depths` Map).\n *\n * @param [startNode=this._root] - The node to start measuring from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The minimum height (-1 for empty, 0 for single node).\n */\n getMinHeight(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): number {\n startNode = this.ensureNode(startNode);\n if (!startNode) return -1;\n\n if (iterationType === 'RECURSIVE') {\n const _getMinHeight = (cur: BinaryTreeNode<K, V> | null | undefined): number => {\n if (!this.isRealNode(cur)) return 0;\n if (!this.isRealNode(cur.left) && !this.isRealNode(cur.right)) return 0; // Leaf node\n const leftMinHeight = _getMinHeight(cur.left);\n const rightMinHeight = _getMinHeight(cur.right);\n return Math.min(leftMinHeight, rightMinHeight) + 1;\n };\n\n return _getMinHeight(startNode);\n } else {\n // Iterative (using post-order DFS)\n const stack: BinaryTreeNode<K, V>[] = [];\n let node: BinaryTreeNode<K, V> | null | undefined = startNode,\n last: BinaryTreeNode<K, V> | null | undefined = null;\n const depths: Map<BinaryTreeNode<K, V>, number> = new Map();\n\n while (stack.length > 0 || node) {\n if (this.isRealNode(node)) {\n stack.push(node);\n node = node.left;\n } else {\n node = stack[stack.length - 1];\n if (!this.isRealNode(node.right) || last === node.right) {\n node = stack.pop();\n if (this.isRealNode(node)) {\n const leftMinHeight = this.isRealNode(node.left) ? depths.get(node.left)! : -1;\n const rightMinHeight = this.isRealNode(node.right) ? depths.get(node.right)! : -1;\n depths.set(node, 1 + Math.min(leftMinHeight, rightMinHeight));\n last = node;\n node = null;\n }\n } else node = node.right;\n }\n }\n\n return depths.get(startNode)!;\n }\n }\n\n getPathToRoot(\n beginNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): (K | undefined)[];\n\n getPathToRoot<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n beginNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n callback: C,\n isReverse?: boolean\n ): ReturnType<C>[];\n\n /**\n * Gets the path from a given node up to the root.\n * @remarks Time O(H), where H is the depth of the `beginNode`. O(N) worst-case. Space O(H) for the result array.\n *\n * @template C - The type of the callback function.\n * @param beginNode - The node to start the path from.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on each node in the path.\n * @param [isReverse=false] - If true, returns the path from root-to-node.\n * @returns An array of callback results.\n */\n getPathToRoot<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n beginNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n isReverse = false\n ): ReturnType<C>[] {\n const result: ReturnType<C>[] = [];\n let beginNodeEnsured = this.ensureNode(beginNode);\n\n if (!beginNodeEnsured) return result;\n\n while (beginNodeEnsured.parent) {\n result.push(callback(beginNodeEnsured));\n beginNodeEnsured = beginNodeEnsured.parent;\n }\n result.push(callback(beginNodeEnsured)); // Add the root\n return isReverse ? result.reverse() : result;\n }\n\n getLeftMost(): K | undefined;\n\n getLeftMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n /**\n * Finds the leftmost node in a subtree (the node with the smallest key in a BST).\n * @remarks Time O(H), where H is the height of the left spine. O(N) worst-case. Space O(H) for recursive/trampoline stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on the leftmost node.\n * @param [startNode=this._root] - The subtree root to search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The callback result for the leftmost node.\n */\n getLeftMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C> {\n if (this.isNIL(startNode)) return callback(undefined);\n const ensuredStartNode = this.ensureNode(startNode);\n\n if (!this.isRealNode(ensuredStartNode)) return callback(undefined);\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {\n const { left } = cur;\n if (!this.isRealNode(left)) return cur;\n return dfs(left);\n };\n\n return callback(dfs(ensuredStartNode));\n } else {\n // Iterative (trampolined to prevent stack overflow, though 'ITERATIVE' usually means a loop)\n const dfs = makeTrampoline((cur: BinaryTreeNode<K, V>): Trampoline<BinaryTreeNode<K, V>> => {\n const { left } = cur;\n if (!this.isRealNode(left)) return cur;\n return makeTrampolineThunk(() => dfs(left));\n });\n\n return callback(dfs(ensuredStartNode));\n }\n }\n\n getRightMost(): K | undefined;\n\n getRightMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n /**\n * Finds the rightmost node in a subtree (the node with the largest key in a BST).\n * @remarks Time O(H), where H is the height of the right spine. O(N) worst-case. Space O(H) for recursive/trampoline stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on the rightmost node.\n * @param [startNode=this._root] - The subtree root to search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The callback result for the rightmost node.\n */\n getRightMost<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C> {\n if (this.isNIL(startNode)) return callback(undefined);\n startNode = this.ensureNode(startNode);\n if (!startNode) return callback(undefined);\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> => {\n const { right } = cur;\n if (!this.isRealNode(right)) return cur;\n return dfs(right);\n };\n\n return callback(dfs(startNode));\n } else {\n const dfs = makeTrampoline((cur: BinaryTreeNode<K, V>): Trampoline<BinaryTreeNode<K, V>> => {\n const { right } = cur;\n if (!this.isRealNode(right)) return cur;\n return makeTrampolineThunk(() => dfs(right));\n });\n\n return callback(dfs(startNode));\n }\n }\n\n /**\n * Gets the Morris traversal predecessor (rightmost node in the left subtree, or node itself).\n * @remarks This is primarily a helper for Morris traversal. Time O(H), where H is the height of the left subtree. O(N) worst-case. Space O(1).\n *\n * @param node - The node to find the predecessor for.\n * @returns The Morris predecessor.\n */\n getPredecessor(node: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> {\n if (this.isRealNode(node.left)) {\n let predecessor: BinaryTreeNode<K, V> | null | undefined = node.left;\n while (!this.isRealNode(predecessor) || (this.isRealNode(predecessor.right) && predecessor.right !== node)) {\n if (this.isRealNode(predecessor)) {\n predecessor = predecessor.right;\n }\n }\n return predecessor;\n } else {\n return node;\n }\n }\n\n /**\n * Gets the in-order successor of a node in a BST.\n * @remarks Time O(H), where H is the tree height. O(N) worst-case. Space O(H) (due to `getLeftMost` stack).\n *\n * @param [x] - The node to find the successor of.\n * @returns The successor node, or null/undefined if none exists.\n */\n getSuccessor(x?: K | BinaryTreeNode<K, V> | null): BinaryTreeNode<K, V> | null | undefined {\n x = this.ensureNode(x);\n if (!this.isRealNode(x)) return undefined;\n\n if (this.isRealNode(x.right)) {\n return this.getLeftMost(node => node, x.right);\n }\n\n let y: BinaryTreeNode<K, V> | null | undefined = x.parent;\n while (this.isRealNode(y) && x === y.right) {\n x = y;\n y = y.parent;\n }\n return y;\n }\n\n dfs(): (K | undefined)[];\n\n dfs<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n dfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback?: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: boolean\n ): ReturnType<C>[];\n\n /**\n * Performs a Depth-First Search (DFS) traversal.\n * @remarks Time O(N), visits every node. Space O(H) for the call/explicit stack. O(N) worst-case.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [pattern='IN'] - The traversal order ('IN', 'PRE', 'POST').\n * @param [onlyOne=false] - If true, stops after the first callback.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @param [includeNull=false] - If true, includes null nodes in the traversal.\n * @returns An array of callback results.\n */\n dfs<C extends NodeCallback<BinaryTreeNode<K, V> | undefined>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n onlyOne: boolean = false,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n return this._dfs(callback, pattern, onlyOne, startNode, iterationType, includeNull);\n }\n\n bfs(): (K | undefined)[];\n\n bfs<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: false\n ): ReturnType<C>[];\n\n bfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: true\n ): ReturnType<C>[];\n\n /**\n * Performs a Breadth-First Search (BFS) or Level-Order traversal.\n * @remarks Time O(N), visits every node. Space O(N) in the worst case for the queue (e.g., a full last level).\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method ('RECURSIVE' BFS is less common but supported here).\n * @param [includeNull=false] - If true, includes null nodes in the traversal.\n * @returns An array of callback results.\n */\n bfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n\n const ans: ReturnType<NodeCallback<BinaryTreeNode<K, V> | null>>[] = [];\n\n if (iterationType === 'RECURSIVE') {\n // This is a \"recursive\" BFS, which is atypical. It uses a queue but calls itself.\n const queue: Queue<OptNodeOrNull<BinaryTreeNode<K, V>>> = new Queue<OptNodeOrNull<BinaryTreeNode<K, V>>>([\n startNode\n ]);\n\n const dfs = (level: number) => {\n if (queue.length === 0) return;\n\n const current = queue.shift()!;\n ans.push(callback(current));\n\n if (includeNull) {\n if (current && this.isRealNodeOrNull(current.left)) queue.push(current.left);\n if (current && this.isRealNodeOrNull(current.right)) queue.push(current.right);\n } else {\n if (this.isRealNode(current.left)) queue.push(current.left);\n if (this.isRealNode(current.right)) queue.push(current.right);\n }\n\n dfs(level + 1);\n };\n\n dfs(0);\n } else {\n // Standard iterative BFS\n const queue = new Queue<OptNodeOrNull<BinaryTreeNode<K, V>>>([startNode]);\n while (queue.length > 0) {\n const levelSize = queue.length; // Not strictly needed here, but good for level-by-level\n for (let i = 0; i < levelSize; i++) {\n const current = queue.shift()!;\n ans.push(callback(current));\n\n if (includeNull) {\n if (current && this.isRealNodeOrNull(current.left)) queue.push(current.left);\n if (current && this.isRealNodeOrNull(current.right)) queue.push(current.right);\n } else {\n if (this.isRealNode(current.left)) queue.push(current.left);\n if (this.isRealNode(current.right)) queue.push(current.right);\n }\n }\n }\n }\n return ans;\n }\n\n leaves(): (K | undefined)[];\n\n leaves<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Finds all leaf nodes in the tree.\n * @remarks Time O(N), visits every node. Space O(H) for recursive stack or O(N) for iterative queue.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each leaf node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n leaves<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n const leaves: ReturnType<NodeCallback<BinaryTreeNode<K, V> | null>>[] = [];\n\n if (!this.isRealNode(startNode)) return [];\n\n if (iterationType === 'RECURSIVE') {\n // DFS-based\n const dfs = (cur: BinaryTreeNode<K, V>) => {\n if (this.isLeaf(cur)) {\n leaves.push(callback(cur));\n }\n if (!this.isRealNode(cur.left) && !this.isRealNode(cur.right)) return;\n if (this.isRealNode(cur.left)) dfs(cur.left);\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(startNode);\n } else {\n // BFS-based\n const queue = new Queue([startNode]);\n\n while (queue.length > 0) {\n const cur = queue.shift();\n if (this.isRealNode(cur)) {\n if (this.isLeaf(cur)) {\n leaves.push(callback(cur));\n }\n if (this.isRealNode(cur.left)) queue.push(cur.left);\n if (this.isRealNode(cur.right)) queue.push(cur.right);\n }\n }\n }\n\n return leaves;\n }\n\n listLevels(): (K | undefined)[][];\n\n listLevels<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: false\n ): ReturnType<C>[][];\n\n listLevels<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback?: C,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: true\n ): ReturnType<C>[][];\n\n /**\n * Returns a 2D array of nodes, grouped by level.\n * @remarks Time O(N), visits every node. Space O(N) for the result array and the queue/stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @param [includeNull=false] - If true, includes null nodes.\n * @returns A 2D array of callback results.\n */\n listLevels<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false\n ): ReturnType<C>[][] {\n startNode = this.ensureNode(startNode);\n const levelsNodes: ReturnType<C>[][] = [];\n\n if (!startNode) return levelsNodes;\n\n if (iterationType === 'RECURSIVE') {\n // Pre-order DFS based level listing\n const _recursive = (node: BinaryTreeNode<K, V> | null, level: number) => {\n if (!levelsNodes[level]) levelsNodes[level] = [];\n levelsNodes[level].push(callback(node));\n if (includeNull) {\n if (node && this.isRealNodeOrNull(node.left)) _recursive(node.left, level + 1);\n if (node && this.isRealNodeOrNull(node.right)) _recursive(node.right, level + 1);\n } else {\n if (node && node.left) _recursive(node.left, level + 1);\n if (node && node.right) _recursive(node.right, level + 1);\n }\n };\n\n _recursive(startNode, 0);\n } else {\n // Iterative DFS based level listing\n const stack: [BinaryTreeNode<K, V> | null, number][] = [[startNode, 0]];\n\n while (stack.length > 0) {\n const head = stack.pop()!;\n const [node, level] = head;\n\n if (!levelsNodes[level]) levelsNodes[level] = [];\n levelsNodes[level].push(callback(node));\n\n if (includeNull) {\n if (node && this.isRealNodeOrNull(node.right)) stack.push([node.right, level + 1]);\n if (node && this.isRealNodeOrNull(node.left)) stack.push([node.left, level + 1]);\n } else {\n if (node && node.right) stack.push([node.right, level + 1]);\n if (node && node.left) stack.push([node.left, level + 1]);\n }\n }\n }\n\n return levelsNodes;\n }\n\n morris(): (K | undefined)[];\n\n morris<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback?: C,\n pattern?: DFSOrderPattern,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): ReturnType<C>[];\n\n /**\n * Performs a Morris (threaded) traversal.\n * @remarks This traversal uses O(1) extra space (excluding the result array) by temporarily modifying the tree's right child pointers. Time O(N), as each node is visited a constant number of times. Space O(1) (excluding the `ans` array).\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [pattern='IN'] - The traversal order ('IN', 'PRE', 'POST').\n * @param [startNode=this._root] - The node to start from.\n * @returns An array of callback results.\n */\n morris<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n\n if (!startNode) return [];\n const ans: ReturnType<NodeCallback<BinaryTreeNode<K, V> | null>>[] = [];\n\n let cur: BinaryTreeNode<K, V> | null | undefined = startNode;\n\n // Helper to reverse a linked list (formed by right pointers)\n const _reverseEdge = (node: BinaryTreeNode<K, V> | null | undefined) => {\n let pre: BinaryTreeNode<K, V> | null | undefined = null;\n let next: BinaryTreeNode<K, V> | null | undefined = null;\n while (node) {\n next = node.right;\n node.right = pre;\n pre = node;\n node = next;\n }\n return pre;\n };\n\n // Helper to print the reversed edge (for post-order)\n const _printEdge = (node: BinaryTreeNode<K, V> | null | undefined) => {\n const tail: BinaryTreeNode<K, V> | null | undefined = _reverseEdge(node);\n let cur: BinaryTreeNode<K, V> | null | undefined = tail;\n\n while (cur) {\n ans.push(callback(cur));\n cur = cur.right;\n }\n\n _reverseEdge(tail); // Restore the edge\n };\n\n switch (pattern) {\n case 'IN':\n while (cur) {\n if (cur.left) {\n const predecessor = this.getPredecessor(cur);\n if (!predecessor.right) {\n // Create thread\n predecessor.right = cur;\n cur = cur.left;\n continue;\n } else {\n // Remove thread\n predecessor.right = null;\n }\n }\n ans.push(callback(cur));\n cur = cur.right;\n }\n break;\n case 'PRE':\n while (cur) {\n if (cur.left) {\n const predecessor = this.getPredecessor(cur);\n if (!predecessor.right) {\n // Create thread and visit\n predecessor.right = cur;\n ans.push(callback(cur));\n cur = cur.left;\n continue;\n } else {\n // Remove thread\n predecessor.right = null;\n }\n } else {\n ans.push(callback(cur));\n }\n cur = cur.right;\n }\n break;\n case 'POST':\n while (cur) {\n if (cur.left) {\n const predecessor = this.getPredecessor(cur);\n if (predecessor.right === null) {\n // Create thread\n predecessor.right = cur;\n cur = cur.left;\n continue;\n } else {\n // Remove thread and print right spine of left child\n predecessor.right = null;\n _printEdge(cur.left);\n }\n }\n cur = cur.right;\n }\n _printEdge(startNode); // Print the right spine of the root\n break;\n }\n return ans;\n }\n\n /**\n * Clones the tree.\n * @remarks Time O(N * M), where N is the number of nodes and M is the tree size during insertion (due to `bfs` + `add`, and `add` is O(M)). Space O(N) for the new tree and the BFS queue.\n *\n * @returns A new, cloned instance of the tree.\n */\n clone(): this {\n const out = this._createInstance<K, V, R>();\n this._clone(out);\n return out;\n }\n\n /**\n * Creates a new tree containing only the entries that satisfy the predicate.\n * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion (O(N) iteration + O(M) `add` for each item). Space O(N) for the new tree.\n *\n * @param predicate - A function to test each [key, value] pair.\n * @param [thisArg] - `this` context for the predicate.\n * @returns A new, filtered tree.\n */\n filter(predicate: EntryCallback<K, V | undefined, boolean>, thisArg?: unknown): this {\n const out = this._createInstance<K, V, R>();\n let i = 0;\n for (const [k, v] of this) if (predicate.call(thisArg, v, k, i++, this)) out.add([k, v]);\n return out;\n }\n\n /**\n * Creates a new tree by mapping each [key, value] pair to a new entry.\n * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion. Space O(N) for the new tree.\n *\n * @template MK - New key type.\n * @template MV - New value type.\n * @template MR - New raw type.\n * @param cb - A function to map each [key, value] pair.\n * @param [options] - Options for the new tree.\n * @param [thisArg] - `this` context for the callback.\n * @returns A new, mapped tree.\n */\n map<MK = K, MV = V, MR = any>(\n cb: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<BinaryTreeOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): BinaryTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let i = 0;\n for (const [k, v] of this) out.add(cb.call(thisArg, v, k, i++, this));\n return out;\n }\n\n /**\n * Generates a string representation of the tree for visualization.\n * @remarks Time O(N), visits every node. Space O(N*H) or O(N^2) in the worst case, as the string width can grow significantly.\n *\n * @param [startNode=this._root] - The node to start printing from.\n * @param [options] - Options to control the output (e.g., show nulls).\n * @returns The string representation of the tree.\n */\n override toVisual(\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n options?: BinaryTreePrintOptions\n ): string {\n const opts = { isShowUndefined: false, isShowNull: true, isShowRedBlackNIL: false, ...options };\n startNode = this.ensureNode(startNode);\n let output = '';\n if (!startNode) return output;\n\n if (opts.isShowUndefined) output += `U for undefined\\n`;\n if (opts.isShowNull) output += `N for null\\n`;\n if (opts.isShowRedBlackNIL) output += `S for Sentinel Node(NIL)\\n`;\n\n const display = (root: BinaryTreeNode<K, V> | null | undefined): void => {\n const [lines] = this._displayAux(root, opts);\n let paragraph = '';\n for (const line of lines) {\n paragraph += line + '\\n';\n }\n output += paragraph;\n };\n\n display(startNode);\n return output;\n }\n\n /**\n * Prints a visual representation of the tree to the console.\n * @remarks Time O(N) (via `toVisual`). Space O(N*H) or O(N^2) (via `toVisual`).\n *\n * @param [options] - Options to control the output.\n * @param [startNode=this._root] - The node to start printing from.\n */\n override print(\n options?: BinaryTreePrintOptions,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root\n ) {\n console.log(this.toVisual(startNode, options));\n }\n\n protected _dfs<C extends NodeCallback<BinaryTreeNode<K, V>>>(\n callback: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType,\n includeNull?: boolean,\n shouldVisitLeft?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean,\n shouldVisitRight?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean,\n shouldVisitRoot?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean,\n shouldProcessRoot?: (node: BinaryTreeNode<K, V> | null | undefined) => boolean\n ): ReturnType<C>[];\n\n /**\n * (Protected) Core DFS implementation.\n * @remarks Time O(N), visits every node satisfying predicates. Space O(H) for call/explicit stack. O(N) worst-case.\n *\n * @template C - Callback type.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on nodes.\n * @param [pattern='IN'] - Traversal order.\n * @param [onlyOne=false] - Stop after first match.\n * @param [startNode=this._root] - Starting node.\n * @param [iterationType=this.iterationType] - Traversal method.\n * @param [includeNull=false] - Include nulls.\n * @param [shouldVisitLeft] - Predicate to traverse left.\n * @param [shouldVisitRight] - Predicate to traverse right.\n * @param [shouldVisitRoot] - Predicate to visit root.\n * @param [shouldProcessRoot] - Predicate to process root.\n * @returns Array of callback results.\n */\n protected _dfs<C extends NodeCallback<BinaryTreeNode<K, V> | null>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n onlyOne: boolean = false,\n startNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType,\n includeNull = false,\n shouldVisitLeft: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => !!node,\n shouldVisitRight: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => !!node,\n shouldVisitRoot: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => {\n if (includeNull) return this.isRealNodeOrNull(node);\n return this.isRealNode(node);\n },\n shouldProcessRoot: (node: BinaryTreeNode<K, V> | null | undefined) => boolean = node => this.isRealNodeOrNull(node)\n ): ReturnType<C>[] {\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n const ans: ReturnType<C>[] = [];\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (node: BinaryTreeNode<K, V> | null) => {\n if (!shouldVisitRoot(node)) return;\n\n const visitLeft = () => {\n if (shouldVisitLeft(node) && node?.left !== undefined) dfs(node?.left);\n };\n const visitRight = () => {\n if (shouldVisitRight(node) && node?.right !== undefined) dfs(node?.right);\n };\n\n switch (pattern) {\n case 'IN':\n visitLeft();\n if (shouldProcessRoot(node)) {\n ans.push(callback(node));\n if (onlyOne) return;\n }\n visitRight();\n break;\n case 'PRE':\n if (shouldProcessRoot(node)) {\n ans.push(callback(node));\n if (onlyOne) return;\n }\n visitLeft();\n visitRight();\n break;\n case 'POST':\n visitLeft();\n visitRight();\n if (shouldProcessRoot(node)) {\n ans.push(callback(node));\n if (onlyOne) return;\n }\n break;\n }\n };\n\n dfs(startNode);\n } else {\n // Iterative\n const stack: DFSStackItem<BinaryTreeNode<K, V>>[] = [{ opt: DFSOperation.VISIT, node: startNode }];\n\n const pushLeft = (cur: DFSStackItem<BinaryTreeNode<K, V>>) => {\n if (shouldVisitLeft(cur.node)) stack.push({ opt: DFSOperation.VISIT, node: cur.node?.left });\n };\n const pushRight = (cur: DFSStackItem<BinaryTreeNode<K, V>>) => {\n if (shouldVisitRight(cur.node)) stack.push({ opt: DFSOperation.VISIT, node: cur.node?.right });\n };\n const pushRoot = (cur: DFSStackItem<BinaryTreeNode<K, V>>) => {\n if (shouldVisitRoot(cur.node)) stack.push({ opt: DFSOperation.PROCESS, node: cur.node });\n };\n\n while (stack.length > 0) {\n const cur = stack.pop();\n if (cur === undefined) continue;\n if (!shouldVisitRoot(cur.node)) continue;\n if (cur.opt === DFSOperation.PROCESS) {\n if (shouldProcessRoot(cur.node) && cur.node !== undefined) {\n ans.push(callback(cur.node));\n if (onlyOne) return ans;\n }\n } else {\n // VISIT\n switch (pattern) {\n case 'IN':\n pushRight(cur);\n pushRoot(cur);\n pushLeft(cur);\n break;\n case 'PRE':\n pushRight(cur);\n pushLeft(cur);\n pushRoot(cur);\n break;\n case 'POST':\n pushRoot(cur);\n pushRight(cur);\n pushLeft(cur);\n break;\n }\n }\n }\n }\n\n return ans;\n }\n\n /**\n * (Protected) Gets the iterator for the tree (default in-order).\n * @remarks Time O(N) for full iteration. O(H) to get the first element. Space O(H) for the iterative stack. O(H) for recursive stack.\n *\n * @param [node=this._root] - The node to start iteration from.\n * @returns An iterator for [key, value] pairs.\n */\n protected *_getIterator(node = this._root): IterableIterator<[K, V | undefined]> {\n if (!node) return;\n\n if (this.iterationType === 'ITERATIVE') {\n const stack: (BinaryTreeNode<K, V> | null | undefined)[] = [];\n let current: BinaryTreeNode<K, V> | null | undefined = node;\n\n while (current || stack.length > 0) {\n // Go to the leftmost node\n while (this.isRealNode(current)) {\n stack.push(current);\n current = current.left;\n }\n\n // Visit the node\n current = stack.pop();\n\n if (this.isRealNode(current)) {\n if (this._isMapMode) yield [current.key, this._store.get(current.key)];\n else yield [current.key, current.value];\n // Move to the right subtree\n current = current.right;\n }\n }\n } else {\n // Recursive in-order traversal\n if (node.left && this.isRealNode(node)) {\n yield* this[Symbol.iterator](node.left);\n }\n\n if (this._isMapMode) yield [node.key, this._store.get(node.key)];\n else yield [node.key, node.value];\n\n if (node.right && this.isRealNode(node)) {\n yield* this[Symbol.iterator](node.right);\n }\n }\n }\n\n /**\n * (Protected) Default callback function, returns the node's key.\n * @remarks Time O(1)\n *\n * @param node - The node.\n * @returns The node's key or undefined.\n */\n protected _DEFAULT_NODE_CALLBACK = (node: BinaryTreeNode<K, V> | null | undefined) => (node ? node.key : undefined);\n\n /**\n * (Protected) Snapshots the current tree's configuration options.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the options.\n * @returns The options object.\n */\n protected _snapshotOptions<TK = K, TV = V, TR = R>(): BinaryTreeOptions<TK, TV, TR> {\n return {\n iterationType: this.iterationType,\n toEntryFn: this.toEntryFn as unknown as BinaryTreeOptions<TK, TV, TR>['toEntryFn'],\n isMapMode: this.isMapMode,\n isDuplicate: this.isDuplicate\n };\n }\n\n /**\n * (Protected) Creates a new, empty instance of the same tree constructor.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [options] - Options for the new tree.\n * @returns A new, empty tree.\n */\n protected _createInstance<TK = K, TV = V, TR = R>(options?: Partial<BinaryTreeOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BinaryTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BinaryTreeOptions<TK, TV, TR>\n ) => BinaryTree<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Creates a new instance of the same tree constructor, potentially with different generic types.\n * @remarks Time O(N) (or as per constructor) due to processing the iterable.\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [iter=[]] - An iterable to populate the new tree.\n * @param [options] - Options for the new tree.\n * @returns A new tree.\n */\n protected _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | BinaryTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<BinaryTreeOptions<TK, TV, TR>>\n ): BinaryTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BinaryTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BinaryTreeOptions<TK, TV, TR>\n ) => BinaryTree<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as BinaryTree<\n TK,\n TV,\n TR\n >;\n }\n\n /**\n * (Protected) Converts a key, node, or entry into a standardized [node, value] tuple.\n * @remarks Time O(1)\n *\n * @param keyNodeOrEntry - The input item.\n * @param [value] - An optional value (used if input is just a key).\n * @returns A tuple of [node, value].\n */\n protected _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): [BinaryTreeNode<K, V> | null | undefined, V | undefined] {\n if (keyNodeOrEntry === undefined) return [undefined, undefined];\n if (keyNodeOrEntry === null) return [null, undefined];\n\n if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, entryValue] = keyNodeOrEntry;\n if (key === undefined) return [undefined, undefined];\n else if (key === null) return [null, undefined];\n const finalValue = value ?? entryValue;\n return [this.createNode(key, finalValue), finalValue];\n }\n\n return [this.createNode(keyNodeOrEntry, value), value];\n }\n\n /**\n * (Protected) Helper for cloning. Performs a BFS and adds all nodes to the new tree.\n * @remarks Time O(N * M) (O(N) BFS + O(M) `add` for each node).\n *\n * @param cloned - The new, empty tree instance to populate.\n */\n protected _clone(cloned: BinaryTree<K, V, R>) {\n // Use BFS with nulls to preserve the tree structure\n this.bfs(\n node => {\n if (node === null) cloned.add(null);\n else {\n if (this._isMapMode) cloned.add([node.key, this._store.get(node.key)]);\n else cloned.add([node.key, node.value]);\n }\n },\n this._root,\n this.iterationType,\n true // Include nulls\n );\n if (this._isMapMode) cloned._store = this._store;\n }\n\n /**\n * (Protected) Recursive helper for `toVisual`.\n * @remarks Time O(N), Space O(N*H) or O(N^2)\n *\n * @param node - The current node.\n * @param options - Print options.\n * @returns Layout information for this subtree.\n */\n protected _displayAux(\n node: BinaryTreeNode<K, V> | null | undefined,\n options: BinaryTreePrintOptions\n ): NodeDisplayLayout {\n const { isShowNull, isShowUndefined, isShowRedBlackNIL } = options;\n const emptyDisplayLayout = <NodeDisplayLayout>[['─'], 1, 0, 0]; // Represents an empty spot\n\n if (node === null && !isShowNull) {\n return emptyDisplayLayout;\n } else if (node === undefined && !isShowUndefined) {\n return emptyDisplayLayout;\n } else if (this.isNIL(node) && !isShowRedBlackNIL) {\n return emptyDisplayLayout;\n } else if (node !== null && node !== undefined) {\n // Real node\n const key = node.key,\n line = this.isNIL(node) ? 'S' : String(key),\n width = line.length;\n\n return _buildNodeDisplay(\n line,\n width,\n this._displayAux(node.left, options),\n this._displayAux(node.right, options)\n );\n } else {\n // Null or Undefined\n const line = node === undefined ? 'U' : 'N',\n width = line.length;\n\n // Treat as a leaf\n return _buildNodeDisplay(line, width, [[''], 1, 0, 0], [[''], 1, 0, 0]);\n }\n\n /**\n * (Inner) Builds the display lines for a node.\n * @remarks Time/Space: Proportional to the width and height of the subtrees.\n */\n function _buildNodeDisplay(line: string, width: number, left: NodeDisplayLayout, right: NodeDisplayLayout) {\n const [leftLines, leftWidth, leftHeight, leftMiddle] = left;\n const [rightLines, rightWidth, rightHeight, rightMiddle] = right;\n const firstLine =\n ' '.repeat(Math.max(0, leftMiddle + 1)) +\n '_'.repeat(Math.max(0, leftWidth - leftMiddle - 1)) +\n line +\n '_'.repeat(Math.max(0, rightMiddle)) +\n ' '.repeat(Math.max(0, rightWidth - rightMiddle));\n\n const secondLine =\n (leftHeight > 0\n ? ' '.repeat(leftMiddle) + '/' + ' '.repeat(leftWidth - leftMiddle - 1)\n : ' '.repeat(leftWidth)) +\n ' '.repeat(width) +\n (rightHeight > 0\n ? ' '.repeat(rightMiddle) + '\\\\' + ' '.repeat(rightWidth - rightMiddle - 1)\n : ' '.repeat(rightWidth));\n\n const mergedLines = [firstLine, secondLine];\n\n for (let i = 0; i < Math.max(leftHeight, rightHeight); i++) {\n const leftLine = i < leftHeight ? leftLines[i] : ' '.repeat(leftWidth);\n const rightLine = i < rightHeight ? rightLines[i] : ' '.repeat(rightWidth);\n mergedLines.push(leftLine + ' '.repeat(width) + rightLine);\n }\n\n return <NodeDisplayLayout>[\n mergedLines,\n leftWidth + width + rightWidth,\n Math.max(leftHeight, rightHeight) + 2,\n leftWidth + Math.floor(width / 2)\n ];\n }\n }\n\n /**\n * (Protected) Swaps the key/value properties of two nodes.\n * @remarks Time O(1)\n *\n * @param srcNode - The source node.\n * @param destNode - The destination node.\n * @returns The `destNode` (now holding `srcNode`'s properties).\n */\n protected _swapProperties(\n srcNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n destNode: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeNode<K, V> | undefined {\n srcNode = this.ensureNode(srcNode);\n destNode = this.ensureNode(destNode);\n\n if (srcNode && destNode) {\n const { key, value } = destNode;\n const tempNode = this.createNode(key, value); // Use a temp node to hold dest properties\n\n if (tempNode) {\n // Copy src to dest\n destNode.key = srcNode.key;\n if (!this._isMapMode) destNode.value = srcNode.value;\n\n // Copy temp (original dest) to src\n srcNode.key = tempNode.key;\n if (!this._isMapMode) srcNode.value = tempNode.value;\n }\n\n return destNode;\n }\n return undefined;\n }\n\n /**\n * (Protected) Replaces a node in the tree with a new node, maintaining children and parent links.\n * @remarks Time O(1)\n *\n * @param oldNode - The node to be replaced.\n * @param newNode - The node to insert.\n * @returns The `newNode`.\n */\n protected _replaceNode(oldNode: BinaryTreeNode<K, V>, newNode: BinaryTreeNode<K, V>): BinaryTreeNode<K, V> {\n if (oldNode.parent) {\n if (oldNode.parent.left === oldNode) {\n oldNode.parent.left = newNode;\n } else if (oldNode.parent.right === oldNode) {\n oldNode.parent.right = newNode;\n }\n }\n newNode.left = oldNode.left;\n newNode.right = oldNode.right;\n newNode.parent = oldNode.parent;\n if (this._root === oldNode) {\n this._setRoot(newNode);\n }\n\n return newNode;\n }\n\n /**\n * (Protected) Sets the root node and clears its parent reference.\n * @remarks Time O(1)\n *\n * @param v - The node to set as root.\n */\n protected _setRoot(v: BinaryTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = undefined;\n }\n this._root = v;\n }\n\n /**\n * (Protected) Converts a key, node, entry, or predicate into a standardized predicate function.\n * @remarks Time O(1)\n *\n * @param keyNodeEntryOrPredicate - The item to convert.\n * @returns A predicate function.\n */\n protected _ensurePredicate(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V>>\n ): NodePredicate<BinaryTreeNode<K, V>>;\n\n protected _ensurePredicate(\n keyNodeEntryOrPredicate:\n | K\n | BinaryTreeNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BinaryTreeNode<K, V> | null>\n ): NodePredicate<BinaryTreeNode<K, V> | null> {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined)\n return (node: BinaryTreeNode<K, V> | null | undefined) => (node ? false : false);\n\n if (this._isPredicate(keyNodeEntryOrPredicate)) return keyNodeEntryOrPredicate;\n\n if (this.isRealNode(keyNodeEntryOrPredicate))\n return (node: BinaryTreeNode<K, V> | null) => node === keyNodeEntryOrPredicate;\n\n if (this.isEntry(keyNodeEntryOrPredicate)) {\n const [key] = keyNodeEntryOrPredicate;\n return (node: BinaryTreeNode<K, V> | null) => {\n if (!node) return false;\n return node.key === key;\n };\n }\n\n // Assume it's a key\n return (node: BinaryTreeNode<K, V> | null) => {\n if (!node) return false;\n return node.key === keyNodeEntryOrPredicate;\n };\n }\n\n /**\n * (Protected) Checks if an item is a predicate function.\n * @remarks Time O(1)\n *\n * @param p - The item to check.\n * @returns True if it's a function.\n */\n protected _isPredicate(p: any): p is NodePredicate<BinaryTreeNode<K, V>> {\n return typeof p === 'function';\n }\n\n /**\n * (Protected) Extracts the key from a key, node, or entry.\n * @remarks Time O(1)\n *\n * @param keyNodeOrEntry - The item.\n * @returns The extracted key.\n */\n protected _extractKey(\n keyNodeOrEntry: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): K | null | undefined {\n if (keyNodeOrEntry === null) return null;\n if (keyNodeOrEntry === undefined) return;\n if (keyNodeOrEntry === this._NIL) return;\n if (this.isNode(keyNodeOrEntry)) return keyNodeOrEntry.key;\n\n if (this.isEntry(keyNodeOrEntry)) return keyNodeOrEntry[0];\n\n return keyNodeOrEntry;\n }\n\n /**\n * (Protected) Sets a value in the external store (Map mode).\n * @remarks Time O(1) (average for Map.set).\n *\n * @param key - The key.\n * @param value - The value.\n * @returns True if successful.\n */\n protected _setValue(key: K | null | undefined, value: V | undefined) {\n if (key === null || key === undefined) return false;\n if (value === undefined) return false; // Or allow setting undefined?\n return this._store.set(key, value);\n }\n\n /**\n * (Protected) Clears all nodes from the tree.\n * @remarks Time O(1)\n */\n protected _clearNodes() {\n this._setRoot(undefined);\n this._size = 0;\n }\n\n /**\n * (Protected) Clears all values from the external store.\n * @remarks Time O(N)\n */\n protected _clearValues() {\n this._store.clear();\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n BSTNOptKeyOrNode,\n BSTOptions,\n BTNRep,\n Comparator,\n CP,\n DFSOrderPattern,\n EntryCallback,\n FamilyPosition,\n IterationType,\n NodeCallback,\n NodePredicate,\n OptNode,\n RBTNColor\n} from '../../types';\nimport { BinaryTree } from './binary-tree';\nimport { IBinaryTree } from '../../interfaces';\nimport { Queue } from '../queue';\nimport { isComparable } from '../../utils';\nimport { Range } from '../../common';\n\n/**\n * Represents a Node in a Binary Search Tree.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n */\nexport class BSTNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: BSTNode<K, V> = undefined;\n\n /**\n * Creates an instance of BSTNode.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key of the node.\n * @param [value] - The value associated with the key.\n */\n constructor(key: K, value?: V) {\n this.key = key;\n this.value = value;\n }\n\n _left?: BSTNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the left child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The left child.\n */\n get left(): BSTNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Sets the left child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the left child.\n */\n set left(v: BSTNode<K, V> | null | undefined) {\n if (v) v.parent = this;\n this._left = v;\n }\n\n _right?: BSTNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the right child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The right child.\n */\n get right(): BSTNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Sets the right child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the right child.\n */\n set right(v: BSTNode<K, V> | null | undefined) {\n if (v) v.parent = this;\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Represents a Binary Search Tree (BST).\n * Keys are ordered, allowing for faster search operations compared to a standard Binary Tree.\n * @template K - The type of the key.\n * @template V - The type of the value.\n * @template R - The type of the raw data object (if using `toEntryFn`).\n *\n * 1. Node Order: Each node's left child has a lesser value, and the right child has a greater value.\n * 2. Unique Keys: No duplicate keys in a standard BST.\n * 3. Efficient Search: Enables quick search, minimum, and maximum operations.\n * 4. Inorder Traversal: Yields nodes in ascending order.\n * 5. Logarithmic Operations: Ideal operations like insertion, deletion, and searching are O(log n) time-efficient.\n * 6. Balance Variability: Can become unbalanced; special types maintain balance.\n * 7. No Auto-Balancing: Standard BSTs don't automatically balance themselves.\n *\n * @example\n * // basic BST creation and add operation\n * // Create a simple BST with numeric keys\n * const bst = new BST<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * bst.print();\n * // _______8__________\n * // / \\\n * // ___4___ ____12_____\n * // / \\ / \\\n * // _2_ _6_ _10__ _14__\n * // / \\ / \\ / \\ / \\\n * // 1 3 5 7 9 11 13 15__\n * // \\\n * // 16\n *\n * // Verify size\n * console.log(bst.size); // 16;\n *\n * // Add new elements\n * bst.add(17);\n * bst.add(0);\n * console.log(bst.size); // 18;\n *\n * // Verify keys are searchable\n * console.log(bst.has(11)); // true;\n * console.log(bst.has(100)); // false;\n * @example\n * // BST delete and search after deletion\n * const bst = new BST<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * // Delete a leaf node\n * bst.delete(1);\n * console.log(bst.has(1)); // false;\n *\n * // Delete a node with one child\n * bst.delete(2);\n * console.log(bst.has(2)); // false;\n *\n * // Delete a node with two children\n * bst.delete(3);\n * console.log(bst.has(3)); // false;\n *\n * // Size decreases with each deletion\n * console.log(bst.size); // 13;\n *\n * // Other nodes remain searchable\n * console.log(bst.has(11)); // true;\n * console.log(bst.has(15)); // true;\n * @example\n * // Merge 3 sorted datasets\n * const dataset1 = new BST<number, string>([\n * [1, 'A'],\n * [7, 'G']\n * ]);\n * const dataset2 = [\n * [2, 'B'],\n * [6, 'F']\n * ];\n * const dataset3 = new BST<number, string>([\n * [3, 'C'],\n * [5, 'E'],\n * [4, 'D']\n * ]);\n *\n * // Merge datasets into a single BinarySearchTree\n * const merged = new BST<number, string>(dataset1);\n * merged.addMany(dataset2);\n * merged.merge(dataset3);\n *\n * // Verify merged dataset is in sorted order\n * console.log([...merged.values()]); // ['A', 'B', 'C', 'D', 'E', 'F', 'G'];\n * @example\n * // BST with custom objects for expression evaluation\n * interface Expression {\n * id: number;\n * operator: string;\n * precedence: number;\n * }\n *\n * // BST efficiently stores and retrieves operators by precedence\n * const operatorTree = new BST<number, Expression>(\n * [\n * [1, { id: 1, operator: '+', precedence: 1 }],\n * [2, { id: 2, operator: '*', precedence: 2 }],\n * [3, { id: 3, operator: '/', precedence: 2 }],\n * [4, { id: 4, operator: '-', precedence: 1 }],\n * [5, { id: 5, operator: '^', precedence: 3 }]\n * ],\n * { isMapMode: false }\n * );\n *\n * console.log(operatorTree.size); // 5;\n *\n * // Quick lookup of operators\n * const mult = operatorTree.get(2);\n * console.log(mult?.operator); // '*';\n * console.log(mult?.precedence); // 2;\n *\n * // Check if operator exists\n * console.log(operatorTree.has(5)); // true;\n * console.log(operatorTree.has(99)); // false;\n *\n * // Retrieve operator by precedence level\n * const expNode = operatorTree.getNode(3);\n * console.log(expNode?.key); // 3;\n * console.log(expNode?.value?.precedence); // 2;\n *\n * // Delete operator and verify\n * operatorTree.delete(1);\n * console.log(operatorTree.has(1)); // false;\n * console.log(operatorTree.size); // 4;\n *\n * // Get tree height for optimization analysis\n * const treeHeight = operatorTree.getHeight();\n * console.log(treeHeight); // > 0;\n *\n * // Remaining operators are still accessible\n * const remaining = operatorTree.get(2);\n * console.log(remaining); // defined;\n * @example\n * // Find lowest common ancestor\n * const bst = new BST<number>([20, 10, 30, 5, 15, 25, 35, 3, 7, 12, 18]);\n *\n * // LCA helper function\n * const findLCA = (num1: number, num2: number): number | undefined => {\n * const path1 = bst.getPathToRoot(num1);\n * const path2 = bst.getPathToRoot(num2);\n * // Find the first common ancestor\n * return findFirstCommon(path1, path2);\n * };\n *\n * function findFirstCommon(arr1: (number | undefined)[], arr2: (number | undefined)[]): number | undefined {\n * for (const num of arr1) {\n * if (arr2.indexOf(num) !== -1) {\n * return num;\n * }\n * }\n * return undefined;\n * }\n *\n * // Assertions\n * console.log(findLCA(3, 10)); // 7;\n * console.log(findLCA(5, 35)); // 15;\n * console.log(findLCA(20, 30)); // 25;\n */\nexport class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Creates an instance of BST.\n * @remarks Time O(N log N) or O(N^2) depending on `isBalanceAdd` in `addMany` and input order. Space O(N).\n *\n * @param [keysNodesEntriesOrRaws=[]] - An iterable of items to add.\n * @param [options] - Configuration options for the BST, including comparator.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<K | BSTNode | [K | null | undefined, V | undefined] | null | undefined | R> = [],\n options?: BSTOptions<K, V, R>\n ) {\n super([], options);\n\n if (options) {\n // Use the 'in' operator to check if the field is present\n if ('comparator' in options && options.comparator !== undefined) {\n this._comparator = options.comparator;\n } else {\n this._comparator = this._createDefaultComparator();\n }\n } else {\n this._comparator = this._createDefaultComparator();\n }\n\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected override _root?: BSTNode<K, V> = undefined;\n\n /**\n * Gets the root node of the tree.\n * @remarks Time O(1)\n *\n * @returns The root node.\n */\n override get root(): OptNode<BSTNode<K, V>> {\n return this._root;\n }\n\n /**\n * The comparator function used to determine the order of keys in the tree.\n\n * @remarks Time O(1) Space O(1)\n */\n protected _comparator: Comparator<K>;\n\n /**\n * Gets the comparator function used by the tree.\n * @remarks Time O(1)\n *\n * @returns The comparator function.\n */\n get comparator(): Comparator<K> {\n return this._comparator;\n }\n\n /**\n * (Protected) Creates a new BST node.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key for the new node.\n * @param [value] - The value for the new node (used if not in Map mode).\n * @returns The newly created BSTNode.\n */\n override createNode(key: K, value?: V): BSTNode<K, V> {\n return new BSTNode<K, V>(key, this._isMapMode ? undefined : value);\n }\n\n /**\n * Ensures the input is a node. If it's a key or entry, it searches for the node.\n * @remarks Time O(log N) (height of the tree), O(N) worst-case.\n *\n * @param keyNodeOrEntry - The item to resolve to a node.\n * @param [iterationType=this.iterationType] - The traversal method to use if searching.\n * @returns The resolved node, or undefined if not found.\n */\n override ensureNode(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType: IterationType = this.iterationType\n ): OptNode<BSTNode<K, V>> {\n return super.ensureNode(keyNodeOrEntry, iterationType) ?? undefined;\n }\n\n /**\n * Checks if the given item is a `BSTNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a BSTNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is BSTNode<K, V> {\n return keyNodeOrEntry instanceof BSTNode;\n }\n\n /**\n * Checks if the given key is valid (comparable).\n * @remarks Time O(1)\n *\n * @param key - The key to validate.\n * @returns True if the key is valid, false otherwise.\n */\n override isValidKey(key: any): key is K {\n return isComparable(key);\n }\n\n override dfs(): (K | undefined)[];\n\n override dfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n pattern?: DFSOrderPattern,\n onlyOne?: boolean,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Performs a Depth-First Search (DFS) traversal.\n * @remarks Time O(N), visits every node. Space O(log N) for the call/explicit stack. O(N) worst-case.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [pattern='IN'] - The traversal order ('IN', 'PRE', 'POST').\n * @param [onlyOne=false] - If true, stops after the first callback.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n override dfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n pattern: DFSOrderPattern = 'IN',\n onlyOne: boolean = false,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n return super.dfs(callback, pattern, onlyOne, startNode, iterationType);\n }\n\n override bfs(): (K | undefined)[];\n override bfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Performs a Breadth-First Search (BFS) or Level-Order traversal.\n * @remarks Time O(N), visits every node. Space O(N) in the worst case for the queue.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n override bfs<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n return super.bfs(callback, startNode, iterationType, false);\n }\n\n override listLevels(): (K | undefined)[][];\n\n override listLevels<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[][];\n\n /**\n * Returns a 2D array of nodes, grouped by level.\n * @remarks Time O(N), visits every node. Space O(N) for the result array and the queue/stack.\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on each node.\n * @param [startNode=this._root] - The node to start from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns A 2D array of callback results.\n */\n override listLevels<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[][] {\n return super.listLevels(callback, startNode, iterationType, false);\n }\n\n /**\n * Gets the first node matching a predicate.\n * @remarks Time O(log N) if searching by key, O(N) if searching by predicate. Space O(log N) or O(N).\n *\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns The first matching node, or undefined if not found.\n */\n override getNode(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n startNode: BSTNOptKeyOrNode<K, BSTNode<K, V>> = this._root,\n iterationType: IterationType = this.iterationType\n ): OptNode<BSTNode<K, V>> {\n return this.getNodes(keyNodeEntryOrPredicate, true, startNode, iterationType)[0] ?? undefined;\n }\n\n override search(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne?: boolean\n ): (K | undefined)[];\n\n override search<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne: boolean,\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Searches the tree for nodes matching a predicate, key, or range.\n * @remarks This is an optimized search for a BST. If searching by key or range, it prunes branches.\n * Time O(H + M) for key/range search (H=height, M=matches). O(N) for predicate search.\n * Space O(log N) for the stack.\n *\n * @template C - The type of the callback function.\n * @param keyNodeEntryOrPredicate - The key, node, entry, predicate, or range to search for.\n * @param [onlyOne=false] - If true, stops after finding the first match.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on matching nodes.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - Whether to use 'RECURSIVE' or 'ITERATIVE' search.\n * @returns An array of results from the callback function for each matching node.\n */\n override search<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne = false,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n if (keyNodeEntryOrPredicate === undefined) return [];\n if (keyNodeEntryOrPredicate === null) return [];\n startNode = this.ensureNode(startNode);\n if (!startNode) return [];\n\n let predicate: NodePredicate<BSTNode<K, V>>;\n const isRange = this.isRange(keyNodeEntryOrPredicate);\n\n if (isRange) {\n predicate = node => {\n if (!node) return false;\n return (keyNodeEntryOrPredicate as Range<K>).isInRange(node.key, this._comparator);\n };\n } else {\n predicate = this._ensurePredicate(keyNodeEntryOrPredicate);\n }\n\n // Optimization: Pruning logic\n const shouldVisitLeft = (cur: BSTNode<K, V> | null | undefined) => {\n if (!cur) return false;\n if (!this.isRealNode(cur.left)) return false;\n if (isRange) {\n // Range search: Only go left if the current key is >= the lower bound\n const range = keyNodeEntryOrPredicate as Range<K>;\n const leftS = range.low;\n const leftI = range.includeLow;\n return (leftI && this._compare(cur.key, leftS) >= 0) || (!leftI && this._compare(cur.key, leftS) > 0);\n }\n if (!isRange && !this._isPredicate(keyNodeEntryOrPredicate)) {\n // Key search: Only go left if current key > target key\n const benchmarkKey = this._extractKey(keyNodeEntryOrPredicate);\n return benchmarkKey !== null && benchmarkKey !== undefined && this._compare(cur.key, benchmarkKey) > 0;\n }\n return true; // Predicate search: must visit all\n };\n\n const shouldVisitRight = (cur: BSTNode<K, V> | null | undefined) => {\n if (!cur) return false;\n if (!this.isRealNode(cur.right)) return false;\n if (isRange) {\n // Range search: Only go right if current key <= upper bound\n const range = keyNodeEntryOrPredicate as Range<K>;\n const rightS = range.high;\n const rightI = range.includeHigh;\n return (rightI && this._compare(cur.key, rightS) <= 0) || (!rightI && this._compare(cur.key, rightS) < 0);\n }\n if (!isRange && !this._isPredicate(keyNodeEntryOrPredicate)) {\n // Key search: Only go right if current key < target key\n const benchmarkKey = this._extractKey(keyNodeEntryOrPredicate);\n return benchmarkKey !== null && benchmarkKey !== undefined && this._compare(cur.key, benchmarkKey) < 0;\n }\n return true; // Predicate search: must visit all\n };\n\n return super._dfs(\n callback,\n 'IN', // In-order is efficient for range/key search\n onlyOne,\n startNode,\n iterationType,\n false,\n shouldVisitLeft,\n shouldVisitRight,\n () => true, // shouldVisitRoot (always visit)\n cur => !!cur && predicate(cur) // shouldProcessRoot (only process if predicate matches)\n );\n }\n\n rangeSearch(range: Range<K> | [K, K]): (K | undefined)[];\n\n rangeSearch<C extends NodeCallback<BSTNode<K, V>>>(\n range: Range<K> | [K, K],\n callback: C,\n startNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Performs an optimized search for nodes within a given key range.\n * @remarks Time O(H + M), where H is tree height and M is the number of matches.\n *\n * @template C - The type of the callback function.\n * @param range - A `Range` object or a `[low, high]` tuple.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - A function to call on matching nodes.\n * @param [startNode=this._root] - The node to start the search from.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n rangeSearch<C extends NodeCallback<BSTNode<K, V>>>(\n range: Range<K> | [K, K],\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ) {\n const searchRange: Range<K> = range instanceof Range ? range : new Range(range[0], range[1]);\n return this.search(searchRange, false, callback, startNode, iterationType);\n }\n\n /**\n * Adds a new node to the BST based on key comparison.\n * @remarks Time O(log N), where H is tree height. O(N) worst-case (unbalanced tree), O(log N) average. Space O(1).\n *\n * @param keyNodeOrEntry - The key, node, or entry to add.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n override add(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (newNode === undefined) return false;\n\n if (this._root === undefined) {\n this._setRoot(newNode);\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n\n let current = this._root;\n while (current !== undefined) {\n if (this._compare(current.key, newNode.key) === 0) {\n // Key exists, replace node\n this._replaceNode(current, newNode);\n if (this._isMapMode) this._setValue(current.key, newValue);\n return true;\n } else if (this._compare(current.key, newNode.key) > 0) {\n // Go left\n if (current.left === undefined) {\n current.left = newNode;\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n if (current.left !== null) current = current.left;\n } else {\n // Go right\n if (current.right === undefined) {\n current.right = newNode;\n if (this._isMapMode) this._setValue(newNode?.key, newValue);\n this._size++;\n return true;\n }\n if (current.right !== null) current = current.right;\n }\n }\n return false;\n }\n\n /**\n * Adds multiple items to the tree.\n * @remarks If `isBalanceAdd` is true, sorts the input and builds a balanced tree. Time O(N log N) (due to sort and balanced add).\n * If false, adds items one by one. Time O(N * H), which is O(N^2) worst-case.\n * Space O(N) for sorting and recursion/iteration stack.\n *\n * @param keysNodesEntriesOrRaws - An iterable of items to add.\n * @param [values] - An optional parallel iterable of values.\n * @param [isBalanceAdd=true] - If true, builds a balanced tree from the items.\n * @param [iterationType=this.iterationType] - The traversal method for balanced add (recursive or iterative).\n * @returns An array of booleans indicating the success of each individual `add` operation.\n */\n override addMany(\n keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, BSTNode<K, V>>>,\n values?: Iterable<V | undefined>,\n isBalanceAdd = true,\n iterationType: IterationType = this.iterationType\n ): boolean[] {\n const inserted: boolean[] = [];\n const valuesIterator: Iterator<V | undefined> | undefined = values?.[Symbol.iterator]();\n\n if (!isBalanceAdd) {\n // Standard O(N*H) insertion\n for (let kve of keysNodesEntriesOrRaws) {\n const val = valuesIterator?.next().value;\n if (this.isRaw(kve)) kve = this._toEntryFn!(kve);\n inserted.push(this.add(kve, val));\n }\n return inserted;\n }\n\n // Balanced O(N log N) insertion\n const realBTNExemplars: {\n key: R | K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined;\n value: V | undefined;\n orgIndex: number;\n }[] = [];\n\n let i = 0;\n for (const kve of keysNodesEntriesOrRaws) {\n realBTNExemplars.push({ key: kve, value: valuesIterator?.next().value, orgIndex: i++ });\n }\n\n // Sort items by key\n const sorted = realBTNExemplars.sort(({ key: a }, { key: b }) => {\n let keyA: K | undefined | null, keyB: K | undefined | null;\n if (this.isRaw(a)) keyA = this._toEntryFn!(a)[0];\n else if (this.isEntry(a)) keyA = a[0];\n else if (this.isRealNode(a)) keyA = a.key;\n else keyA = a as K;\n\n if (this.isRaw(b)) keyB = this._toEntryFn!(b)[0];\n else if (this.isEntry(b)) keyB = b[0];\n else if (this.isRealNode(b)) keyB = b.key;\n else keyB = b as K;\n\n if (keyA != null && keyB != null) return this._compare(keyA, keyB);\n return 0;\n });\n\n // Recursive balanced build\n const _dfs = (arr: typeof realBTNExemplars) => {\n if (arr.length === 0) return;\n const mid = Math.floor((arr.length - 1) / 2);\n const { key, value, orgIndex } = arr[mid];\n if (this.isRaw(key)) {\n const entry = this._toEntryFn!(key);\n inserted[orgIndex] = this.add(entry);\n } else {\n inserted[orgIndex] = this.add(key, value);\n }\n _dfs(arr.slice(0, mid));\n _dfs(arr.slice(mid + 1));\n };\n\n // Iterative balanced build\n const _iterate = () => {\n const n = sorted.length;\n const stack: Array<[number, number]> = [[0, n - 1]];\n while (stack.length > 0) {\n const popped = stack.pop();\n if (!popped) continue;\n const [l, r] = popped;\n if (l > r) continue;\n const m = l + Math.floor((r - l) / 2);\n const { key, value, orgIndex } = sorted[m];\n if (this.isRaw(key)) {\n const entry = this._toEntryFn!(key);\n inserted[orgIndex] = this.add(entry);\n } else {\n inserted[orgIndex] = this.add(key, value);\n }\n stack.push([m + 1, r]);\n stack.push([l, m - 1]);\n }\n };\n\n if (iterationType === 'RECURSIVE') _dfs(sorted);\n else _iterate();\n\n return inserted;\n }\n\n /**\n * Returns the first key with a value >= target.\n * Equivalent to Java TreeMap.ceiling.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n ceiling(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key >= target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n ceiling<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n ceiling<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n const node = this._bound(keyNodeEntryOrPredicate, true, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n /**\n * Returns the first key with a value > target.\n * Equivalent to Java TreeMap.higher.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n higher(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key > target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n higher<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n higher<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n const node = this._bound(keyNodeEntryOrPredicate, false, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n /**\n * Returns the first key with a value <= target.\n * Equivalent to Java TreeMap.floor.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n floor(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key <= target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n floor<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n floor<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n if (this._isPredicate(keyNodeEntryOrPredicate)) {\n const node = this._floorByPredicate(keyNodeEntryOrPredicate, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n let targetKey: K | undefined;\n if (this.isNode(keyNodeEntryOrPredicate)) {\n targetKey = keyNodeEntryOrPredicate.key;\n } else if (this.isEntry(keyNodeEntryOrPredicate)) {\n const key = keyNodeEntryOrPredicate[0];\n if (key === null || key === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n targetKey = key;\n } else {\n targetKey = keyNodeEntryOrPredicate;\n }\n\n if (targetKey !== undefined) {\n const node = this._floorByKey(targetKey, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n /**\n * Returns the first key with a value < target.\n * Equivalent to Java TreeMap.lower.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n lower(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n ): K | undefined;\n\n /**\n * Returns the first node with a key < target and applies callback.\n * Time Complexity: O(log n) average, O(h) worst case.\n * Space Complexity: O(h) for recursion, O(1) for iteration.\n */\n lower<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback: C,\n iterationType?: IterationType\n ): ReturnType<C>;\n\n lower<C extends NodeCallback<BSTNode<K, V>>>(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n callback?: C | IterationType,\n iterationType?: IterationType\n ): K | undefined | ReturnType<C> {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n let actualCallback: C | undefined = undefined;\n let actualIterationType: IterationType = this.iterationType;\n\n if (typeof callback === 'string') {\n actualIterationType = callback;\n } else if (callback) {\n actualCallback = callback;\n if (iterationType) {\n actualIterationType = iterationType;\n }\n }\n\n if (this._isPredicate(keyNodeEntryOrPredicate)) {\n const node = this._lowerByPredicate(keyNodeEntryOrPredicate, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n let targetKey: K | undefined;\n if (this.isNode(keyNodeEntryOrPredicate)) {\n targetKey = keyNodeEntryOrPredicate.key;\n } else if (this.isEntry(keyNodeEntryOrPredicate)) {\n const key = keyNodeEntryOrPredicate[0];\n if (key === null || key === undefined) {\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n targetKey = key;\n } else {\n targetKey = keyNodeEntryOrPredicate;\n }\n\n if (targetKey !== undefined) {\n const node = this._lowerByKey(targetKey, actualIterationType);\n\n if (!actualCallback) {\n return node?.key;\n }\n\n return node ? actualCallback(node) : undefined;\n }\n\n if (typeof callback === 'string' || !callback) {\n return undefined;\n }\n return undefined;\n }\n\n lesserOrGreaterTraverse(): (K | undefined)[];\n\n lesserOrGreaterTraverse<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C,\n lesserOrGreater?: number,\n targetNode?: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n iterationType?: IterationType\n ): ReturnType<C>[];\n\n /**\n * Traverses the tree and returns nodes that are lesser or greater than a target node.\n * @remarks Time O(N), as it performs a full traversal. Space O(log N) or O(N).\n *\n * @template C - The type of the callback function.\n * @param [callback=this._DEFAULT_NODE_CALLBACK] - Function to call on matching nodes.\n * @param [lesserOrGreater=-1] - -1 for lesser, 1 for greater, 0 for equal.\n * @param [targetNode=this._root] - The node to compare against.\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns An array of callback results.\n */\n lesserOrGreaterTraverse<C extends NodeCallback<BSTNode<K, V>>>(\n callback: C = this._DEFAULT_NODE_CALLBACK as C,\n lesserOrGreater: CP = -1,\n targetNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): ReturnType<C>[] {\n const targetNodeEnsured = this.ensureNode(targetNode);\n const ans: ReturnType<NodeCallback<BSTNode<K, V>>>[] = [];\n if (!this._root || !targetNodeEnsured) return ans;\n\n const targetKey = targetNodeEnsured.key;\n\n if (iterationType === 'RECURSIVE') {\n const dfs = (cur: BSTNode<K, V>) => {\n const compared = this._compare(cur.key, targetKey);\n if (Math.sign(compared) == lesserOrGreater) ans.push(callback(cur));\n\n if (this.isRealNode(cur.left)) dfs(cur.left);\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n dfs(this._root);\n return ans;\n } else {\n const queue = new Queue<BSTNode<K, V>>([this._root]);\n while (queue.length > 0) {\n const cur = queue.shift();\n if (this.isRealNode(cur)) {\n const compared = this._compare(cur.key, targetKey);\n if (Math.sign(compared) == lesserOrGreater) ans.push(callback(cur));\n if (this.isRealNode(cur.left)) queue.push(cur.left);\n if (this.isRealNode(cur.right)) queue.push(cur.right);\n }\n }\n return ans;\n }\n }\n\n /**\n * Rebuilds the tree to be perfectly balanced.\n * @remarks Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.\n *\n * @param [iterationType=this.iterationType] - The traversal method for the initial node export.\n * @returns True if successful, false if the tree was empty.\n */\n perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n this._clearNodes();\n if (n === 0) return false;\n\n // Build balanced tree from sorted array\n const build = (l: number, r: number, parent?: BSTNode<K, V>): BSTNode<K, V> | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m]! as BSTNode<K, V>;\n const leftChild = build(l, m - 1, root);\n const rightChild = build(m + 1, r, root);\n root.left = leftChild;\n root.right = rightChild;\n root.parent = parent;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n return true;\n }\n\n /**\n * Checks if the tree meets the AVL balance condition (height difference <= 1).\n * @remarks Time O(N), as it must visit every node to compute height. Space O(log N) for recursion or O(N) for iterative map.\n *\n * @param [iterationType=this.iterationType] - The traversal method.\n * @returns True if the tree is AVL balanced, false otherwise.\n */\n isAVLBalanced(iterationType: IterationType = this.iterationType): boolean {\n if (!this._root) return true;\n let balanced = true;\n\n if (iterationType === 'RECURSIVE') {\n // Recursive height check\n const _height = (cur: BSTNode<K, V> | null | undefined): number => {\n if (!cur) return 0;\n const leftHeight = _height(cur.left);\n const rightHeight = _height(cur.right);\n if (Math.abs(leftHeight - rightHeight) > 1) balanced = false;\n return Math.max(leftHeight, rightHeight) + 1;\n };\n _height(this._root);\n } else {\n // Iterative post-order height check\n const stack: BSTNode<K, V>[] = [];\n let node: OptNode<BSTNode<K, V>> = this._root,\n last: OptNode<BSTNode<K, V>> = undefined;\n const depths: Map<BSTNode<K, V>, number> = new Map();\n\n while (stack.length > 0 || node) {\n if (node) {\n stack.push(node);\n if (node.left !== null) node = node.left;\n } else {\n node = stack[stack.length - 1];\n if (!node.right || last === node.right) {\n node = stack.pop();\n if (node) {\n const left = node.left ? depths.get(node.left)! : -1;\n const right = node.right ? depths.get(node.right)! : -1;\n if (Math.abs(left - right) > 1) return false;\n depths.set(node, 1 + Math.max(left, right));\n last = node;\n node = undefined;\n }\n } else node = node.right;\n }\n }\n }\n return balanced;\n }\n\n /**\n * Creates a new BST by mapping each [key, value] pair to a new entry.\n * @remarks Time O(N * H), where N is nodes in this tree, and H is height of the new tree during insertion.\n * Space O(N) for the new tree.\n *\n * @template MK - New key type.\n * @template MV - New value type.\n * @template MR - New raw type.\n * @param callback - A function to map each [key, value] pair.\n * @param [options] - Options for the new BST.\n * @param [thisArg] - `this` context for the callback.\n * @returns A new, mapped BST.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<BSTOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): BST<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let index = 0;\n // Iterates in-order\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * Deletes nodes that match a key, node, entry, predicate, or range.\n *\n * @remarks\n * Time Complexity: O(N) for search + O(M log N) for M deletions, where N is tree size.\n * Space Complexity: O(M) for storing matched nodes and result map.\n *\n * @template K - The key type.\n * @template V - The value type.\n *\n * @param keyNodeEntryOrPredicate - The search criteria. Can be one of:\n * - A key (type K): searches for exact key match using the comparator.\n * - A BSTNode: searches for the matching node in the tree.\n * - An entry tuple: searches for the key-value pair.\n * - A NodePredicate function: tests each node and returns true for matches.\n * - A Range object: searches for nodes whose keys fall within the specified range (inclusive/exclusive based on range settings).\n * - null or undefined: treated as no match, returns empty results.\n *\n * @param onlyOne - If true, stops the search after finding the first match and only deletes that one node.\n * If false (default), searches for and deletes all matching nodes.\n *\n * @param startNode - The node to start the search from. Can be:\n * - A key, node, or entry: the method resolves it to a node and searches from that subtree.\n * - null or undefined: defaults to the root, searching the entire tree.\n * - Default value: this._root (the tree's root).\n *\n * @param iterationType - Controls the internal traversal implementation:\n * - 'RECURSIVE': uses recursive function calls for traversal.\n * - 'ITERATIVE': uses explicit stack-based iteration.\n * - Default: this.iterationType (the tree's default iteration mode).\n *\n * @returns A Map<K, boolean> containing the deletion results:\n * - Key: the matched node's key.\n * - Value: true if the deletion succeeded, false if it failed (e.g., key not found during deletion phase).\n * - If no nodes match the search criteria, the returned map is empty.\n */\n deleteWhere(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>\n | Range<K>,\n onlyOne = false,\n startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,\n iterationType: IterationType = this.iterationType\n ): BinaryTreeDeleteResult<BSTNode<K, V>>[] {\n const toDelete = this.search(keyNodeEntryOrPredicate, onlyOne, node => node, startNode, iterationType);\n\n let results: BinaryTreeDeleteResult<BSTNode<K, V>>[] = [];\n for (const node of toDelete) {\n const deleteInfo = this.delete(node);\n results = results.concat(deleteInfo);\n }\n\n return results;\n }\n\n /**\n * (Protected) Creates the default comparator function for keys that don't have a custom comparator.\n * @remarks Time O(1) Space O(1)\n * @returns The default comparator function.\n */\n protected _createDefaultComparator(): Comparator<K> {\n return (a: K, b: K): number => {\n debugger;\n // If both keys are comparable (primitive types), use direct comparison\n if (isComparable(a) && isComparable(b)) {\n if (a > b) return 1;\n if (a < b) return -1;\n return 0;\n }\n\n // If keys are objects and no comparator is provided, throw an error\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object type keys, a custom comparator must be provided in the constructor's options!`\n );\n }\n\n // Default: keys are equal (fallback case)\n return 0;\n };\n }\n\n /**\n * (Protected) Binary search for floor by key with pruning optimization.\n * Performs standard BST binary search, choosing left or right subtree based on comparator result.\n * Finds first node where key <= target.\n * @remarks Time O(h) where h is tree height.\n *\n * @param key - The target key to search for.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node with key <= target, or undefined if none exists.\n */\n protected _floorByKey(key: K, iterationType: IterationType): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive binary search implementation\n const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {\n if (!this.isRealNode(cur)) return undefined;\n\n const cmp = this.comparator(cur.key!, key);\n\n if (cmp <= 0) {\n // Current node satisfies the floor condition (cur.key <= target).\n // Try to find a larger candidate in the right subtree.\n const rightResult = dfs(cur.right);\n return rightResult ?? cur;\n } else {\n // Current node is too large, move left to find smaller keys.\n return dfs(cur.left);\n }\n };\n\n return dfs(this.root);\n } else {\n // Iterative binary search implementation\n let current: BSTNode<K, V> | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (this.isRealNode(current)) {\n const cmp = this.comparator(current.key!, key);\n\n if (cmp <= 0) {\n // Current node is a candidate. Save it and try right subtree for a larger key.\n result = current;\n current = current.right ?? undefined;\n } else {\n // Current node is too large, move left.\n current = current.left ?? undefined;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) In-order traversal search for floor by predicate.\n * Falls back to linear in-order traversal when predicate-based search is required.\n * Returns the last node that satisfies the predicate function.\n * @remarks Time Complexity: O(n) since it may visit every node.\n * Space Complexity: O(h) for recursion, O(h) for iterative stack.\n *\n * @param predicate - The predicate function to test nodes.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The last node satisfying predicate (highest key), or undefined if none found.\n */\n protected _floorByPredicate(\n predicate: NodePredicate<BSTNode<K, V>>,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive in-order traversal\n let result: BSTNode<K, V> | undefined = undefined;\n\n const dfs = (cur: BSTNode<K, V> | null | undefined): void => {\n if (!this.isRealNode(cur)) return;\n\n // In-order: process left subtree first\n if (this.isRealNode(cur.left)) dfs(cur.left);\n\n // Check current node\n if (predicate(cur)) {\n result = cur;\n }\n\n // Process right subtree\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(this.root);\n return result;\n } else {\n // Iterative in-order traversal using explicit stack\n const stack: (BSTNode<K, V> | null | undefined)[] = [];\n let current: BSTNode<K, V> | null | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (stack.length > 0 || this.isRealNode(current)) {\n if (this.isRealNode(current)) {\n // Go to the leftmost node\n stack.push(current);\n current = current.left;\n } else {\n // Pop from stack and process\n const node = stack.pop();\n if (!this.isRealNode(node)) break;\n\n // Check if current node satisfies predicate\n if (predicate(node)) {\n result = node;\n }\n\n // Visit right subtree\n current = node.right;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) Binary search for lower by key with pruning optimization.\n * Performs standard BST binary search, choosing left or right subtree based on comparator result.\n * Finds first node where key < target.\n * @remarks Time O(h) where h is tree height.\n *\n * @param key - The target key to search for.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node with key < target, or undefined if none exists.\n */\n protected _lowerByKey(key: K, iterationType: IterationType): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive binary search implementation\n const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {\n if (!this.isRealNode(cur)) return undefined;\n\n const cmp = this.comparator(cur.key!, key);\n\n if (cmp < 0) {\n // Current node satisfies the lower condition (cur.key < target).\n // Try to find a larger candidate in the right subtree.\n const rightResult = dfs(cur.right);\n return rightResult ?? cur;\n } else {\n // Current node is too large or equal, move left to find smaller keys.\n return dfs(cur.left);\n }\n };\n\n return dfs(this.root);\n } else {\n // Iterative binary search implementation\n let current: BSTNode<K, V> | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (this.isRealNode(current)) {\n const cmp = this.comparator(current.key!, key);\n\n if (cmp < 0) {\n // Current node is a candidate. Save it and try right subtree for a larger key.\n result = current;\n current = current.right ?? undefined;\n } else {\n // Current node is too large or equal, move left.\n current = current.left ?? undefined;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) In-order traversal search for lower by predicate.\n * Falls back to linear in-order traversal when predicate-based search is required.\n * Returns the node that satisfies the predicate and appears last in in-order traversal.\n * @remarks Time Complexity: O(n) since it may visit every node.\n * Space Complexity: O(h) for recursion, O(h) for iterative stack.\n *\n * @param predicate - The predicate function to test nodes.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The last node satisfying predicate (highest key < target), or undefined if none found.\n */\n protected _lowerByPredicate(\n predicate: NodePredicate<BSTNode<K, V>>,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive in-order traversal\n let result: BSTNode<K, V> | undefined = undefined;\n\n const dfs = (cur: BSTNode<K, V> | null | undefined): void => {\n if (!this.isRealNode(cur)) return;\n\n // In-order: process left subtree first\n if (this.isRealNode(cur.left)) dfs(cur.left);\n\n // Check current node\n if (predicate(cur)) {\n result = cur;\n }\n\n // Process right subtree\n if (this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(this.root);\n return result;\n } else {\n // Iterative in-order traversal using explicit stack\n const stack: (BSTNode<K, V> | null | undefined)[] = [];\n let current: BSTNode<K, V> | null | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (stack.length > 0 || this.isRealNode(current)) {\n if (this.isRealNode(current)) {\n // Go to the leftmost node\n stack.push(current);\n current = current.left;\n } else {\n // Pop from stack and process\n const node = stack.pop();\n if (!this.isRealNode(node)) break;\n\n // Check if current node satisfies predicate\n if (predicate(node)) {\n result = node;\n }\n\n // Visit right subtree\n current = node.right;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) Core bound search implementation supporting all parameter types.\n * Unified logic for both lowerBound and upperBound.\n * Resolves various input types (Key, Node, Entry, Predicate) using parent class utilities.\n * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.\n * @param isLower - True for lowerBound (>=), false for upperBound (>).\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first matching node, or undefined if no such node exists.\n */\n protected _bound(\n keyNodeEntryOrPredicate:\n | K\n | BSTNode<K, V>\n | [K | null | undefined, V | undefined]\n | null\n | undefined\n | NodePredicate<BSTNode<K, V>>,\n isLower: boolean,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {\n return undefined;\n }\n\n // Check if input is a predicate function first\n if (this._isPredicate(keyNodeEntryOrPredicate)) {\n return this._boundByPredicate(keyNodeEntryOrPredicate, iterationType);\n }\n\n // Resolve input to a comparable key\n let targetKey: K | undefined;\n\n if (this.isNode(keyNodeEntryOrPredicate)) {\n // Input is a BSTNode - extract its key\n targetKey = keyNodeEntryOrPredicate.key;\n } else if (this.isEntry(keyNodeEntryOrPredicate)) {\n // Input is a [key, value] entry - extract the key\n const key = keyNodeEntryOrPredicate[0];\n if (key === null || key === undefined) {\n return undefined;\n }\n targetKey = key;\n } else {\n // Input is a raw key\n targetKey = keyNodeEntryOrPredicate;\n }\n\n // Execute key-based search with binary search optimization\n if (targetKey !== undefined) {\n return this._boundByKey(targetKey, isLower, iterationType);\n }\n\n return undefined;\n }\n\n /**\n * (Protected) Binary search for bound by key with pruning optimization.\n * Performs standard BST binary search, choosing left or right subtree based on comparator result.\n * For lowerBound: finds first node where key >= target.\n * For upperBound: finds first node where key > target.\n * @param key - The target key to search for.\n * @param isLower - True for lowerBound (>=), false for upperBound (>).\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node matching the bound condition, or undefined if none exists.\n */\n protected _boundByKey(key: K, isLower: boolean, iterationType: IterationType): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive binary search implementation\n const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {\n if (!this.isRealNode(cur)) return undefined;\n\n const cmp = this.comparator(cur.key!, key);\n const condition = isLower ? cmp >= 0 : cmp > 0;\n\n if (condition) {\n // Current node satisfies the bound condition.\n // Try to find a closer (smaller key) candidate in the left subtree.\n const leftResult = dfs(cur.left);\n return leftResult ?? cur;\n } else {\n // Current node does not satisfy the condition.\n // Move right to find larger keys.\n return dfs(cur.right);\n }\n };\n\n return dfs(this.root);\n } else {\n // Iterative binary search implementation\n let current: BSTNode<K, V> | undefined = this.root;\n let result: BSTNode<K, V> | undefined = undefined;\n\n while (this.isRealNode(current)) {\n const cmp = this.comparator(current.key!, key);\n const condition = isLower ? cmp >= 0 : cmp > 0;\n\n if (condition) {\n // Current node is a candidate. Save it and try left subtree for a closer match.\n result = current;\n current = current.left ?? undefined;\n } else {\n // Move right to find larger keys.\n current = current.right ?? undefined;\n }\n }\n\n return result;\n }\n }\n\n /**\n * (Protected) In-order traversal search by predicate.\n * Falls back to linear in-order traversal when predicate-based search is required.\n * Returns the first node that satisfies the predicate function.\n * Note: Predicate-based search cannot leverage BST's binary search optimization.\n * Time Complexity: O(n) since it may visit every node.\n * @param predicate - The predicate function to test nodes.\n * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).\n * @returns The first node satisfying predicate, or undefined if none found.\n */\n protected _boundByPredicate(\n predicate: NodePredicate<BSTNode<K, V>>,\n iterationType: IterationType\n ): BSTNode<K, V> | undefined {\n if (iterationType === 'RECURSIVE') {\n // Recursive in-order traversal\n let result: BSTNode<K, V> | undefined = undefined;\n\n const dfs = (cur: BSTNode<K, V> | null | undefined): void => {\n if (result || !this.isRealNode(cur)) return;\n\n // In-order: process left subtree first\n if (this.isRealNode(cur.left)) dfs(cur.left);\n\n // Check current node\n if (!result && predicate(cur)) {\n result = cur;\n }\n\n // Process right subtree\n if (!result && this.isRealNode(cur.right)) dfs(cur.right);\n };\n\n dfs(this.root);\n return result;\n } else {\n // Iterative in-order traversal using explicit stack\n const stack: (BSTNode<K, V> | null | undefined)[] = [];\n let current: BSTNode<K, V> | null | undefined = this.root;\n\n while (stack.length > 0 || this.isRealNode(current)) {\n if (this.isRealNode(current)) {\n // Go to the leftmost node\n stack.push(current);\n current = current.left;\n } else {\n // Pop from stack and process\n const node = stack.pop();\n if (!this.isRealNode(node)) break;\n\n // Check if current node satisfies predicate\n if (predicate(node)) {\n return node;\n }\n\n // Visit right subtree\n current = node.right;\n }\n }\n\n return undefined;\n }\n }\n\n /**\n * (Protected) Creates a new, empty instance of the same BST constructor.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [options] - Options for the new BST.\n * @returns A new, empty BST.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<BSTOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BSTOptions<TK, TV, TR>\n ) => BST<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Creates a new instance of the same BST constructor, potentially with different generic types.\n * @remarks Time O(N log N) or O(N^2) (from constructor) due to processing the iterable.\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [iter=[]] - An iterable to populate the new BST.\n * @param [options] - Options for the new BST.\n * @returns A new BST.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<BSTOptions<TK, TV, TR>>\n ): BST<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: BSTOptions<TK, TV, TR>\n ) => BST<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n /**\n * (Protected) Snapshots the current BST's configuration options.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the options.\n * @returns The options object.\n */\n protected override _snapshotOptions<TK = K, TV = V, TR = R>(): BSTOptions<TK, TV, TR> {\n return {\n ...super._snapshotOptions<TK, TV, TR>(),\n comparator: this._comparator as unknown as BSTOptions<TK, TV, TR>['comparator']\n };\n }\n\n /**\n * (Protected) Converts a key, node, or entry into a standardized [node, value] tuple.\n * @remarks Time O(1)\n *\n * @param keyNodeOrEntry - The input item.\n * @param [value] - An optional value (used if input is just a key).\n * @returns A tuple of [node, value].\n */\n protected override _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): [OptNode<BSTNode<K, V>>, V | undefined] {\n const [node, entryValue] = super._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (node === null) return [undefined, undefined]; // BST handles null differently (as undefined)\n return [node, value ?? entryValue];\n }\n\n /**\n * (Protected) Sets the root node and clears its parent reference.\n * @remarks Time O(1)\n *\n * @param v - The node to set as root.\n */\n protected override _setRoot(v: OptNode<BSTNode<K, V>>) {\n if (v) v.parent = undefined;\n this._root = v;\n }\n\n /**\n * (Protected) Compares two keys using the tree's comparator and reverse setting.\n * @remarks Time O(1) Space O(1)\n *\n * @param a - The first key.\n * @param b - The second key.\n * @returns A number (1, -1, or 0) representing the comparison.\n */\n protected _compare(a: K, b: K) {\n return this._comparator(a, b);\n }\n\n /**\n * (Private) Deletes a node by its key.\n * @remarks Standard BST deletion algorithm. Time O(log N), O(N) worst-case. Space O(1).\n *\n * @param key - The key of the node to delete.\n * @returns True if the node was found and deleted, false otherwise.\n */\n protected _deleteByKey(key: K): boolean {\n let node = this._root as BSTNode<K, V> | undefined;\n\n // 1. Find the node\n while (node) {\n const cmp = this._compare(node.key, key);\n if (cmp === 0) break;\n node = cmp > 0 ? (node.left as BSTNode<K, V> | undefined) : (node.right as BSTNode<K, V> | undefined);\n }\n if (!node) return false; // Not found\n\n // Helper to replace node `u` with node `v`\n const transplant = (u: BSTNode<K, V> | undefined, v: BSTNode<K, V> | undefined) => {\n const p = u?.parent as BSTNode<K, V> | undefined;\n if (!p) {\n this._setRoot(v);\n } else if (p.left === u) {\n p.left = v;\n } else {\n p.right = v;\n }\n if (v) v.parent = p;\n };\n\n // Helper to find the minimum node in a subtree\n const minNode = (x: BSTNode<K, V> | undefined): BSTNode<K, V> | undefined => {\n if (!x) return undefined;\n while (x.left !== undefined && x.left !== null) x = x.left as BSTNode<K, V>;\n return x;\n };\n\n // 2. Perform deletion\n if (node.left === undefined) {\n // Case 1: No left child\n transplant(node, node.right as BSTNode<K, V> | undefined);\n } else if (node.right === undefined) {\n // Case 2: No right child\n transplant(node, node.left as BSTNode<K, V> | undefined);\n } else {\n // Case 3: Two children\n const succ = minNode(node.right as BSTNode<K, V> | undefined)!; // Find successor\n if (succ.parent !== node) {\n transplant(succ, succ.right as BSTNode<K, V> | undefined);\n succ.right = node.right as BSTNode<K, V> | undefined;\n if (succ.right) (succ.right as BSTNode<K, V>).parent = succ;\n }\n transplant(node, succ);\n succ.left = node.left as BSTNode<K, V> | undefined;\n if (succ.left) (succ.left as BSTNode<K, V>).parent = succ;\n }\n\n this._size = Math.max(0, ((this as any)._size ?? 0) - 1);\n return true;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport { getMSB } from '../../utils';\n\n/**\n *\n */\nexport class BinaryIndexedTree {\n protected readonly _freq: number;\n protected readonly _max: number;\n\n /**\n * The constructor initializes the properties of an object, including default frequency, maximum\n * value, a freqMap data structure, the most significant bit, and the count of negative frequencies.\n * @param - - `frequency`: The default frequency value. It is optional and has a default\n * value of 0.\n */\n constructor({ frequency = 0, max }: { frequency?: number; max: number }) {\n this._freq = frequency;\n this._max = max;\n this._freqMap = { 0: 0 };\n this._msb = getMSB(max);\n this._negativeCount = frequency < 0 ? max : 0;\n }\n\n protected _freqMap: Record<number, number>;\n\n /**\n * The function returns the frequency map of numbers.\n * @returns The `_freqMap` property, which is a record with number keys and number values, is being\n * returned.\n */\n get freqMap(): Record<number, number> {\n return this._freqMap;\n }\n\n protected _msb: number;\n\n /**\n * The function returns the value of the _msb property.\n * @returns The `_msb` property of the object.\n */\n get msb(): number {\n return this._msb;\n }\n\n protected _negativeCount: number;\n\n /**\n * The function returns the value of the _negativeCount property.\n * @returns The method is returning the value of the variable `_negativeCount`, which is of type\n * `number`.\n */\n get negativeCount(): number {\n return this._negativeCount;\n }\n\n /**\n * The above function returns the value of the protected variable `_freq`.\n * @returns The frequency value stored in the protected variable `_freq`.\n */\n get freq(): number {\n return this._freq;\n }\n\n /**\n * The above function returns the maximum value.\n * @returns The maximum value stored in the variable `_max`.\n */\n get max(): number {\n return this._max;\n }\n\n /**\n * The function \"readSingle\" reads a single number from a specified index.\n * @param {number} index - The `index` parameter is a number that represents the index of an element in a\n * collection or array.\n * @returns a number.\n */\n readSingle(index: number): number {\n this._checkIndex(index);\n return this._readSingle(index);\n }\n\n /**\n * The \"update\" function updates the value at a given index by adding a delta and triggers a callback\n * to notify of the change.\n * @param {number} position - The `index` parameter represents the index of the element that needs to be\n * updated in the data structure.\n * @param {number} change - The \"delta\" parameter represents the change in value that needs to be\n * applied to the frequency at the specified index.\n */\n update(position: number, change: number): void {\n this._checkIndex(position);\n const freqCur = this._readSingle(position);\n\n this._update(position, change);\n this._updateNegativeCount(freqCur, freqCur + change);\n }\n\n /**\n * The function \"writeSingle\" checks the index and writes a single value with a given frequency.\n * @param {number} index - The `index` parameter is a number that represents the index of an element. It\n * is used to identify the specific element that needs to be written.\n * @param {number} freq - The `freq` parameter represents the frequency value that needs to be\n * written.\n */\n writeSingle(index: number, freq: number): void {\n this._checkIndex(index);\n this._writeSingle(index, freq);\n }\n\n /**\n * The read function takes a count parameter, checks if it is an integer, and returns the result of\n * calling the _read function with the count parameter clamped between 0 and the maximum value.\n * @param {number} count - The `count` parameter is a number that represents the number of items to\n * read.\n * @returns a number.\n */\n read(count: number): number {\n if (!Number.isInteger(count)) {\n throw new Error('Invalid count');\n }\n return this._read(Math.max(Math.min(count, this.max), 0));\n }\n\n /**\n * The function returns the lower bound of a non-descending sequence that sums up to a given number.\n * @param {number} sum - The `sum` parameter is a number that represents the target sum that we want\n * to find in the sequence.\n * @returns The lowerBound function is returning a number.\n */\n lowerBound(sum: number): number {\n if (this.negativeCount > 0) {\n throw new Error('Sequence is not non-descending');\n }\n return this._binarySearch(sum, (x, y) => x < y);\n }\n\n /**\n * The upperBound function returns the index of the first element in a sequence that is greater than\n * or equal to a given sum.\n * @param {number} sum - The \"sum\" parameter is a number that represents the target sum that we want\n * to find in the sequence.\n * @returns The upperBound function is returning a number.\n */\n upperBound(sum: number): number {\n if (this.negativeCount > 0) {\n throw new Error('Must not be descending');\n }\n return this._binarySearch(sum, (x, y) => x <= y);\n }\n\n /**\n * The function calculates the prefix sum of an array using a binary indexed tree.\n * @param {number} i - The parameter \"i\" in the function \"getPrefixSum\" represents the index of the element in the\n * array for which we want to calculate the prefix sum.\n * @returns The function `getPrefixSum` returns the prefix sum of the elements in the binary indexed tree up to index\n * `i`.\n */\n getPrefixSum(i: number): number {\n this._checkIndex(i);\n i++; // Convert to 1-based index\n\n let sum = 0;\n while (i > 0) {\n sum += this._getFrequency(i);\n i -= i & -i;\n }\n\n return sum;\n }\n\n /**\n * The function returns the value of a specific index in a freqMap data structure, or a default value if\n * the index is not found.\n * @param {number} index - The `index` parameter is a number that represents the index of a node in a\n * freqMap data structure.\n * @returns a number.\n */\n protected _getFrequency(index: number): number {\n if (index in this.freqMap) {\n return this.freqMap[index];\n }\n\n return this.freq * (index & -index);\n }\n\n /**\n * The function _updateFrequency adds a delta value to the element at the specified index in the freqMap array.\n * @param {number} index - The index parameter is a number that represents the index of the freqMap\n * element that needs to be updated.\n * @param {number} delta - The `delta` parameter represents the change in value that needs to be\n * added to the freqMap at the specified `index`.\n */\n protected _updateFrequency(index: number, delta: number): void {\n this.freqMap[index] = this._getFrequency(index) + delta;\n }\n\n /**\n * The function checks if the given index is valid and within the range.\n * @param {number} index - The parameter \"index\" is of type number and represents the index value\n * that needs to be checked.\n */\n protected _checkIndex(index: number): void {\n if (!Number.isInteger(index)) {\n throw new Error('Invalid index: Index must be an integer.');\n }\n if (index < 0 || index >= this.max) {\n throw new Error('Index out of range: Index must be within the range [0, this.max).');\n }\n }\n\n /**\n * The function calculates the sum of elements in an array up to a given index using a binary indexed\n * freqMap.\n * @param {number} index - The `index` parameter is a number that represents the index of an element in a\n * data structure.\n * @returns a number.\n */\n protected _readSingle(index: number): number {\n index = index + 1;\n let sum = this._getFrequency(index);\n const z = index - (index & -index);\n\n index--;\n\n while (index !== z) {\n sum -= this._getFrequency(index);\n index -= index & -index;\n }\n\n return sum;\n }\n\n /**\n * The function `_updateNegativeCount` updates a counter based on changes in frequency values.\n * @param {number} freqCur - The current frequency value.\n * @param {number} freqNew - The freqNew parameter represents the new frequency value.\n */\n protected _updateNegativeCount(freqCur: number, freqNew: number): void {\n if (freqCur < 0 && freqNew >= 0) {\n this._negativeCount--;\n } else if (freqCur >= 0 && freqNew < 0) {\n this._negativeCount++;\n }\n }\n\n /**\n * The `_update` function updates the values in a binary indexed freqMap starting from a given index and\n * propagating the changes to its parent nodes.\n * @param {number} index - The `index` parameter is a number that represents the index of the element in\n * the data structure that needs to be updated.\n * @param {number} delta - The `delta` parameter represents the change in value that needs to be\n * applied to the elements in the data structure.\n */\n protected _update(index: number, delta: number): void {\n index = index + 1;\n\n while (index <= this.max) {\n this._updateFrequency(index, delta);\n index += index & -index;\n }\n }\n\n /**\n * The `_writeSingle` function updates the frequency at a specific index and triggers a callback if\n * the frequency has changed.\n * @param {number} index - The `index` parameter is a number that represents the index of the element\n * being modified or accessed.\n * @param {number} freq - The `freq` parameter represents the new frequency value that needs to be\n * written to the specified index `index`.\n */\n protected _writeSingle(index: number, freq: number): void {\n const freqCur = this._readSingle(index);\n\n this._update(index, freq - freqCur);\n this._updateNegativeCount(freqCur, freq);\n }\n\n /**\n * The `_read` function calculates the sum of values in a binary freqMap up to a given count.\n * @param {number} count - The `count` parameter is a number that represents the number of elements\n * to read from the freqMap.\n * @returns the sum of the values obtained from calling the `_getFrequency` method for each index in the\n * range from `count` to 1.\n */\n protected _read(count: number): number {\n let index = count;\n let sum = 0;\n while (index) {\n sum += this._getFrequency(index);\n index -= index & -index;\n }\n\n return sum;\n }\n\n /**\n * The function `_binarySearch` performs a binary search to find the largest number that satisfies a given\n * condition.\n * @param {number} sum - The sum parameter is a number that represents the target sum value.\n * @param before - The `before` parameter is a function that takes two numbers `x` and `y` as\n * arguments and returns a boolean value. It is used to determine if `x` is less than or equal to\n * `y`. The purpose of this function is to compare two numbers and determine their order.\n * @returns the value of the variable \"left\".\n */\n protected _binarySearch(sum: number, before: (x: number, y: number) => boolean): number {\n let left = 0;\n let right = this.msb << 1;\n let sumT = sum;\n\n while (right > left + 1) {\n const middle = (left + right) >> 1;\n const sumM = this._getFrequency(middle);\n\n if (middle <= this.max && before(sumM, sumT)) {\n sumT -= sumM;\n left = middle;\n } else {\n right = middle;\n }\n }\n return left;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { SegmentTreeNodeVal } from '../../types';\n\nexport class SegmentTreeNode {\n /**\n * The constructor initializes the properties of a SegmentTreeNode object.\n * @param {number} start - The `start` parameter represents the starting index of the segment covered\n * by this node in a segment tree.\n * @param {number} end - The `end` parameter represents the end index of the segment covered by this\n * node in a segment tree.\n * @param {number} sum - The `sum` parameter represents the sum of the values in the range covered by\n * the segment tree node.\n * @param {SegmentTreeNodeVal | undefined} [value] - The `value` parameter is an optional parameter\n * of type `SegmentTreeNodeVal`. It represents the value associated with the segment tree node.\n */\n constructor(start: number, end: number, sum: number, value?: SegmentTreeNodeVal | undefined) {\n this._start = start;\n this._end = end;\n this._sum = sum;\n this._value = value || undefined;\n }\n\n protected _start = 0;\n\n /**\n * The function returns the value of the protected variable _start.\n * @returns The start value, which is of type number.\n */\n get start(): number {\n return this._start;\n }\n\n /**\n * The above function sets the value of the \"start\" property.\n * @param {number} value - The value parameter is of type number.\n */\n set start(value: number) {\n this._start = value;\n }\n\n protected _end = 0;\n\n /**\n * The function returns the value of the protected variable `_end`.\n * @returns The value of the protected property `_end`.\n */\n get end(): number {\n return this._end;\n }\n\n /**\n * The above function sets the value of the \"end\" property.\n * @param {number} value - The value parameter is a number that represents the new value for the end\n * property.\n */\n set end(value: number) {\n this._end = value;\n }\n\n protected _value: SegmentTreeNodeVal | undefined = undefined;\n\n /**\n * The function returns the value of a segment tree node.\n * @returns The value being returned is either a `SegmentTreeNodeVal` object or `undefined`.\n */\n get value(): SegmentTreeNodeVal | undefined {\n return this._value;\n }\n\n /**\n * The function sets the value of a segment tree node.\n * @param {SegmentTreeNodeVal | undefined} value - The `value` parameter is of type\n * `SegmentTreeNodeVal` or `undefined`.\n */\n set value(value: SegmentTreeNodeVal | undefined) {\n this._value = value;\n }\n\n protected _sum = 0;\n\n /**\n * The function returns the value of the sum property.\n * @returns The method is returning the value of the variable `_sum`.\n */\n get sum(): number {\n return this._sum;\n }\n\n /**\n * The above function sets the value of the sum property.\n * @param {number} value - The parameter \"value\" is of type \"number\".\n */\n set sum(value: number) {\n this._sum = value;\n }\n\n protected _left: SegmentTreeNode | undefined = undefined;\n\n /**\n * The function returns the left child of a segment tree node.\n * @returns The `left` property of the `SegmentTreeNode` object is being returned. It is of type\n * `SegmentTreeNode` or `undefined`.\n */\n get left(): SegmentTreeNode | undefined {\n return this._left;\n }\n\n /**\n * The function sets the value of the left property of a SegmentTreeNode object.\n * @param {SegmentTreeNode | undefined} value - The value parameter is of type SegmentTreeNode or\n * undefined.\n */\n set left(value: SegmentTreeNode | undefined) {\n this._left = value;\n }\n\n protected _right: SegmentTreeNode | undefined = undefined;\n\n /**\n * The function returns the right child of a segment tree node.\n * @returns The `getRight()` method is returning a value of type `SegmentTreeNode` or `undefined`.\n */\n get right(): SegmentTreeNode | undefined {\n return this._right;\n }\n\n /**\n * The function sets the right child of a segment tree node.\n * @param {SegmentTreeNode | undefined} value - The `value` parameter is of type `SegmentTreeNode |\n * undefined`. This means that it can accept either a `SegmentTreeNode` object or `undefined` as its\n * value.\n */\n set right(value: SegmentTreeNode | undefined) {\n this._right = value;\n }\n}\n\nexport class SegmentTree {\n /**\n * The constructor initializes the values, start, end, and root properties of an object.\n * @param {number[]} values - An array of numbers that will be used to build a binary search tree.\n * @param {number} [start] - The `start` parameter is the index of the first element in the `values` array that should\n * be included in the range. If no value is provided for `start`, it defaults to 0, which means the range starts from\n * the beginning of the array.\n * @param {number} [end] - The \"end\" parameter is the index of the last element in the \"values\" array that should be\n * included in the range. If not provided, it defaults to the index of the last element in the \"values\" array.\n */\n constructor(values: number[], start?: number, end?: number) {\n start = start || 0;\n end = end || values.length - 1;\n this._values = values;\n this._start = start;\n this._end = end;\n\n if (values.length > 0) {\n this._root = this.build(start, end);\n } else {\n this._root = undefined;\n this._values = [];\n }\n }\n\n protected _values: number[] = [];\n\n /**\n * The function returns an array of numbers.\n * @returns An array of numbers is being returned.\n */\n get values(): number[] {\n return this._values;\n }\n\n protected _start = 0;\n\n /**\n * The function returns the value of the protected variable _start.\n * @returns The start value, which is of type number.\n */\n get start(): number {\n return this._start;\n }\n\n protected _end: number;\n\n /**\n * The function returns the value of the protected variable `_end`.\n * @returns The value of the protected property `_end`.\n */\n get end(): number {\n return this._end;\n }\n\n protected _root: SegmentTreeNode | undefined;\n\n /**\n * The function returns the root node of a segment tree.\n * @returns The `root` property of the class `SegmentTreeNode` or `undefined` if it is not defined.\n */\n get root(): SegmentTreeNode | undefined {\n return this._root;\n }\n\n /**\n * The build function creates a segment tree by recursively dividing the given range into smaller segments and assigning\n * the sum of values to each segment.\n * @param {number} start - The `start` parameter represents the starting index of the segment or range for which we are\n * building the segment tree.\n * @param {number} end - The \"end\" parameter represents the ending index of the segment or range for which we want to\n * build a segment tree.\n * @returns a SegmentTreeNode object.\n */\n build(start: number, end: number): SegmentTreeNode {\n if (start > end) {\n return new SegmentTreeNode(start, end, 0);\n }\n if (start === end) return new SegmentTreeNode(start, end, this._values[start]);\n\n const mid = start + Math.floor((end - start) / 2);\n const left = this.build(start, mid);\n const right = this.build(mid + 1, end);\n const cur = new SegmentTreeNode(start, end, left.sum + right.sum);\n cur.left = left;\n cur.right = right;\n return cur;\n }\n\n /**\n * The function updates the value of a node in a segment tree and recalculates the sum of its children if they exist.\n * @param {number} index - The index parameter represents the index of the node in the segment tree that needs to be\n * updated.\n * @param {number} sum - The `sum` parameter represents the new value that should be assigned to the `sum` property of\n * the `SegmentTreeNode` at the specified `index`.\n * @param {SegmentTreeNodeVal} [value] - The `value` parameter is an optional value that can be assigned to the `value`\n * property of the `SegmentTreeNode` object. It is not currently used in the code, but you can uncomment the line `//\n * cur.value = value;` and pass a value for `value` in the\n * @returns The function does not return anything.\n */\n updateNode(index: number, sum: number, value?: SegmentTreeNodeVal) {\n const root = this.root || undefined;\n if (!root) {\n return;\n }\n const dfs = (cur: SegmentTreeNode, index: number, sum: number, value?: SegmentTreeNodeVal) => {\n if (cur.start === cur.end && cur.start === index) {\n cur.sum = sum;\n if (value !== undefined) cur.value = value;\n return;\n }\n const mid = cur.start + Math.floor((cur.end - cur.start) / 2);\n if (index <= mid) {\n if (cur.left) {\n dfs(cur.left, index, sum, value);\n }\n } else {\n if (cur.right) {\n dfs(cur.right, index, sum, value);\n }\n }\n if (cur.left && cur.right) {\n cur.sum = cur.left.sum + cur.right.sum;\n }\n };\n\n dfs(root, index, sum, value);\n }\n\n /**\n * The function `querySumByRange` calculates the sum of values within a given range in a segment tree.\n * @param {number} indexA - The starting index of the range for which you want to calculate the sum.\n * @param {number} indexB - The parameter `indexB` represents the ending index of the range for which you want to\n * calculate the sum.\n * @returns The function `querySumByRange` returns a number.\n */\n querySumByRange(indexA: number, indexB: number): number {\n const root = this.root || undefined;\n if (!root) {\n return 0;\n }\n\n if (indexA < 0 || indexB >= this.values.length || indexA > indexB) {\n return NaN;\n }\n\n const dfs = (cur: SegmentTreeNode, i: number, j: number): number => {\n if (i <= cur.start && j >= cur.end) {\n // The range [i, j] completely covers the current node's range [cur.start, cur.end]\n return cur.sum;\n }\n const mid = cur.start + Math.floor((cur.end - cur.start) / 2);\n if (j <= mid) {\n if (cur.left) {\n return dfs(cur.left, i, j);\n } else {\n return NaN;\n }\n } else if (i > mid) {\n if (cur.right) {\n return dfs(cur.right, i, j);\n } else {\n return NaN;\n }\n } else {\n // Query both left and right subtrees\n let leftSum = 0;\n let rightSum = 0;\n if (cur.left) {\n leftSum = dfs(cur.left, i, mid);\n }\n if (cur.right) {\n rightSum = dfs(cur.right, mid + 1, j);\n }\n return leftSum + rightSum;\n }\n };\n return dfs(root, indexA, indexB);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport { BST } from './bst';\nimport type {\n AVLTreeOptions,\n BinaryTreeDeleteResult,\n BinaryTreeOptions,\n BSTNOptKeyOrNode,\n EntryCallback,\n FamilyPosition,\n IterationType,\n RBTNColor\n} from '../../types';\nimport { IBinaryTree } from '../../interfaces';\n\n/**\n * Represents a Node in an AVL (Adelson-Velsky and Landis) Tree.\n * It extends a BSTNode and ensures the 'height' property is maintained.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n */\nexport class AVLTreeNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: AVLTreeNode<K, V> = undefined;\n\n /**\n * Creates an instance of AVLTreeNode.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key of the node.\n * @param [value] - The value associated with the key.\n */\n constructor(key: K, value?: V) {\n this.key = key;\n this.value = value;\n }\n\n _left?: AVLTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the left child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The left child.\n */\n get left(): AVLTreeNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Sets the left child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the left child.\n */\n set left(v: AVLTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: AVLTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Gets the right child of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The right child.\n */\n get right(): AVLTreeNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Sets the right child of the node and updates its parent reference.\n * @remarks Time O(1), Space O(1)\n *\n * @param v - The node to set as the right child.\n */\n set right(v: AVLTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Represents a self-balancing AVL (Adelson-Velsky and Landis) Tree.\n * This tree extends BST and performs rotations on add/delete to maintain balance.\n *\n * @template K - The type of the key.\n * @template V - The type of the value.\n * @template R - The type of the raw data object (if using `toEntryFn`).\n *\n * 1. Height-Balanced: Each node's left and right subtrees differ in height by no more than one.\n * 2. Automatic Rebalancing: AVL trees rebalance themselves automatically during insertions and deletions.\n * 3. Rotations for Balancing: Utilizes rotations (single or double) to maintain balance after updates.\n * 4. Order Preservation: Maintains the binary search tree property where left child values are less than the parent, and right child values are greater.\n * 5. Efficient Lookups: Offers O(log n) search time, where 'n' is the number of nodes, due to its balanced nature.\n * 6. Complex Insertions and Deletions: Due to rebalancing, these operations are more complex than in a regular BST.\n * 7. Path Length: The path length from the root to any leaf is longer compared to an unbalanced BST, but shorter than a linear chain of nodes.\n *\n * @example\n * // basic AVLTree creation and add operation\n * // Create a simple AVLTree with initial values\n * const tree = new AVLTree([5, 2, 8, 1, 9]);\n *\n * tree.print();\n * // _2___\n * // / \\\n * // 1 _8_\n * // / \\\n * // 5 9\n *\n * // Verify the tree maintains sorted order\n * console.log([...tree.keys()]); // [1, 2, 5, 8, 9];\n *\n * // Check size\n * console.log(tree.size); // 5;\n *\n * // Add a new element\n * tree.add(3);\n * console.log(tree.size); // 6;\n * console.log([...tree.keys()]); // [1, 2, 3, 5, 8, 9];\n * @example\n * // AVLTree has and get operations\n * const tree = new AVLTree<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * // Check if element exists\n * console.log(tree.has(6)); // true;\n * console.log(tree.has(99)); // false;\n *\n * // Get node by key\n * const node = tree.getNode(6);\n * console.log(node?.key); // 6;\n *\n * // Verify tree is balanced\n * console.log(tree.isAVLBalanced()); // true;\n * @example\n * // AVLTree delete and balance verification\n * const tree = new AVLTree([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);\n *\n * // Delete an element\n * tree.delete(10);\n * console.log(tree.has(10)); // false;\n *\n * // Tree should remain balanced after deletion\n * console.log(tree.isAVLBalanced()); // true;\n *\n * // Size decreased\n * console.log(tree.size); // 15;\n *\n * // Remaining elements are still sorted\n * const keys = [...tree.keys()];\n * console.log(keys); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16];\n * @example\n * // AVLTree for university ranking system with strict balance\n * interface University {\n * name: string;\n * rank: number;\n * students: number;\n * }\n *\n * // AVLTree provides highest search efficiency with strict balance\n * // (every node's left/right subtrees differ by at most 1 in height)\n * const universityTree = new AVLTree<number, University>([\n * [1, { name: 'MIT', rank: 1, students: 1200 }],\n * [5, { name: 'Stanford', rank: 5, students: 1800 }],\n * [3, { name: 'Harvard', rank: 3, students: 2300 }],\n * [2, { name: 'Caltech', rank: 2, students: 400 }],\n * [4, { name: 'CMU', rank: 4, students: 1500 }]\n * ]);\n *\n * // Quick lookup by rank\n * const mit = universityTree.get(1);\n * console.log(mit?.name); // 'MIT';\n *\n * const cmulevel = universityTree.getHeight(4);\n * console.log(typeof cmulevel); // 'number';\n *\n * // Tree maintains strict balance during insertions and deletions\n * console.log(universityTree.isAVLBalanced()); // true;\n *\n * // Add more universities\n * universityTree.add(6, { name: 'Oxford', rank: 6, students: 2000 });\n * console.log(universityTree.isAVLBalanced()); // true;\n *\n * // Delete and verify balance is maintained\n * universityTree.delete(2);\n * console.log(universityTree.has(2)); // false;\n * console.log(universityTree.isAVLBalanced()); // true;\n *\n * // Get all remaining universities in rank order\n * const remainingRanks = [...universityTree.keys()];\n * console.log(remainingRanks); // [1, 3, 4, 5, 6];\n * console.log(universityTree.size); // 5;\n * @example\n * // Find elements in a range\n * // In interval queries, AVL trees, with their strictly balanced structure and lower height, offer better query efficiency, making them ideal for frequent and high-performance interval queries. In contrast, Red-Black trees, with lower update costs, are more suitable for scenarios involving frequent insertions and deletions where the requirements for interval queries are less demanding.\n * type Datum = { timestamp: Date; temperature: number };\n * // Fixed dataset of CPU temperature readings\n * const cpuData: Datum[] = [\n * { timestamp: new Date('2024-12-02T00:00:00'), temperature: 55.1 },\n * { timestamp: new Date('2024-12-02T00:01:00'), temperature: 56.3 },\n * { timestamp: new Date('2024-12-02T00:02:00'), temperature: 54.8 },\n * { timestamp: new Date('2024-12-02T00:03:00'), temperature: 57.2 },\n * { timestamp: new Date('2024-12-02T00:04:00'), temperature: 58.0 },\n * { timestamp: new Date('2024-12-02T00:05:00'), temperature: 59.4 },\n * { timestamp: new Date('2024-12-02T00:06:00'), temperature: 60.1 },\n * { timestamp: new Date('2024-12-02T00:07:00'), temperature: 61.3 },\n * { timestamp: new Date('2024-12-02T00:08:00'), temperature: 62.0 },\n * { timestamp: new Date('2024-12-02T00:09:00'), temperature: 63.5 },\n * { timestamp: new Date('2024-12-02T00:10:00'), temperature: 64.0 },\n * { timestamp: new Date('2024-12-02T00:11:00'), temperature: 62.8 },\n * { timestamp: new Date('2024-12-02T00:12:00'), temperature: 61.5 },\n * { timestamp: new Date('2024-12-02T00:13:00'), temperature: 60.2 },\n * { timestamp: new Date('2024-12-02T00:14:00'), temperature: 59.8 },\n * { timestamp: new Date('2024-12-02T00:15:00'), temperature: 58.6 },\n * { timestamp: new Date('2024-12-02T00:16:00'), temperature: 57.4 },\n * { timestamp: new Date('2024-12-02T00:17:00'), temperature: 56.2 },\n * { timestamp: new Date('2024-12-02T00:18:00'), temperature: 55.7 },\n * { timestamp: new Date('2024-12-02T00:19:00'), temperature: 54.5 },\n * { timestamp: new Date('2024-12-02T00:20:00'), temperature: 53.2 },\n * { timestamp: new Date('2024-12-02T00:21:00'), temperature: 52.8 },\n * { timestamp: new Date('2024-12-02T00:22:00'), temperature: 51.9 },\n * { timestamp: new Date('2024-12-02T00:23:00'), temperature: 50.5 },\n * { timestamp: new Date('2024-12-02T00:24:00'), temperature: 49.8 },\n * { timestamp: new Date('2024-12-02T00:25:00'), temperature: 48.7 },\n * { timestamp: new Date('2024-12-02T00:26:00'), temperature: 47.5 },\n * { timestamp: new Date('2024-12-02T00:27:00'), temperature: 46.3 },\n * { timestamp: new Date('2024-12-02T00:28:00'), temperature: 45.9 },\n * { timestamp: new Date('2024-12-02T00:29:00'), temperature: 45.0 }\n * ];\n *\n * // Create an AVL tree to store CPU temperature data\n * const cpuTemperatureTree = new AVLTree<Date, number, Datum>(cpuData, {\n * toEntryFn: ({ timestamp, temperature }) => [timestamp, temperature]\n * });\n *\n * // Query a specific time range (e.g., from 00:05 to 00:15)\n * const rangeStart = new Date('2024-12-02T00:05:00');\n * const rangeEnd = new Date('2024-12-02T00:15:00');\n * const rangeResults = cpuTemperatureTree.rangeSearch([rangeStart, rangeEnd], node => ({\n * minute: node ? node.key.getMinutes() : 0,\n * temperature: cpuTemperatureTree.get(node ? node.key : undefined)\n * }));\n *\n * console.log(rangeResults); // [\n * // { minute: 5, temperature: 59.4 },\n * // { minute: 6, temperature: 60.1 },\n * // { minute: 7, temperature: 61.3 },\n * // { minute: 8, temperature: 62 },\n * // { minute: 9, temperature: 63.5 },\n * // { minute: 10, temperature: 64 },\n * // { minute: 11, temperature: 62.8 },\n * // { minute: 12, temperature: 61.5 },\n * // { minute: 13, temperature: 60.2 },\n * // { minute: 14, temperature: 59.8 },\n * // { minute: 15, temperature: 58.6 }\n * // ];\n */\nexport class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Creates an instance of AVLTree.\n * @remarks Time O(N log N) (from `addMany` with balanced add). Space O(N).\n *\n * @param [keysNodesEntriesOrRaws=[]] - An iterable of items to add.\n * @param [options] - Configuration options for the AVL tree.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: AVLTreeOptions<K, V, R>\n ) {\n super([], options);\n // Note: super.addMany is called, which in BST defaults to balanced add.\n if (keysNodesEntriesOrRaws) super.addMany(keysNodesEntriesOrRaws);\n }\n\n /**\n * (Protected) Creates a new AVL tree node.\n * @remarks Time O(1), Space O(1)\n *\n * @param key - The key for the new node.\n * @param [value] - The value for the new node.\n * @returns The newly created AVLTreeNode.\n */\n override createNode(key: K, value?: V): AVLTreeNode<K, V> {\n return new AVLTreeNode<K, V>(key, this._isMapMode ? undefined : value) as AVLTreeNode<K, V>;\n }\n\n /**\n * Checks if the given item is an `AVLTreeNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's an AVLTreeNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is AVLTreeNode<K, V> {\n return keyNodeOrEntry instanceof AVLTreeNode;\n }\n\n /**\n * Adds a new node to the AVL tree and balances the tree path.\n * @remarks Time O(log N) (O(H) for BST add + O(H) for `_balancePath`). Space O(H) for path/recursion.\n *\n * @param keyNodeOrEntry - The key, node, or entry to add.\n * @param [value] - The value, if providing just a key.\n * @returns True if the addition was successful, false otherwise.\n */\n override add(\n keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n if (keyNodeOrEntry === null) return false;\n const inserted = super.add(keyNodeOrEntry, value);\n // If insertion was successful, balance the path from the new node up to the root.\n if (inserted) this._balancePath(keyNodeOrEntry);\n return inserted;\n }\n\n /**\n * Deletes a node from the AVL tree and re-balances the tree.\n * @remarks Time O(log N) (O(H) for BST delete + O(H) for `_balancePath`). Space O(H) for path/recursion.\n *\n * @param keyNodeOrEntry - The node to delete.\n * @returns An array containing deletion results.\n */\n override delete(\n keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeDeleteResult<AVLTreeNode<K, V>>[] {\n const deletedResults = super.delete(keyNodeOrEntry);\n // After deletion, balance the path from the parent of the *physically deleted* node.\n for (const { needBalanced } of deletedResults) {\n if (needBalanced) {\n this._balancePath(needBalanced);\n }\n }\n return deletedResults;\n }\n\n /**\n * Rebuilds the tree to be perfectly balanced.\n * @remarks AVL trees are already height-balanced, but this makes them *perfectly* balanced (minimal height and all leaves at N or N-1).\n * Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.\n *\n * @param [iterationType=this.iterationType] - The traversal method for the initial node export.\n * @returns True if successful, false if the tree was empty.\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n === 0) return false;\n\n this._clearNodes();\n\n // Build balanced tree from sorted array\n const build = (l: number, r: number, parent?: AVLTreeNode<K, V>): AVLTreeNode<K, V> | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m]!;\n root.left = build(l, m - 1, root);\n root.right = build(m + 1, r, root);\n root.parent = parent;\n\n // Update height during the build\n const lh = root.left ? (root.left as AVLTreeNode<K, V>).height : -1;\n const rh = root.right ? (root.right as AVLTreeNode<K, V>).height : -1;\n root.height = Math.max(lh, rh) + 1;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n return true;\n }\n\n /**\n * Creates a new AVLTree by mapping each [key, value] pair.\n * @remarks Time O(N log N) (O(N) iteration + O(log M) `add` for each item into the new tree). Space O(N) for the new tree.\n *\n * @template MK - New key type.\n * @template MV - New value type.\n * @template MR - New raw type.\n * @param callback - A function to map each [key, value] pair.\n * @param [options] - Options for the new AVLTree.\n * @param [thisArg] - `this` context for the callback.\n * @returns A new, mapped AVLTree.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<BinaryTreeOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n // Iterates in-order\n for (const [key, value] of this) {\n // `add` on the new tree will be O(log N) and will self-balance.\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * (Protected) Creates a new, empty instance of the same AVLTree constructor.\n * @remarks Time O(1)\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [options] - Options for the new tree.\n * @returns A new, empty tree.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<AVLTreeOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeOptions<TK, TV, TR>\n ) => this;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Creates a new instance of the same AVLTree constructor, potentially with different generic types.\n * @remarks Time O(N log N) (from constructor) due to processing the iterable.\n *\n * @template TK, TV, TR - Generic types for the new instance.\n * @param [iter=[]] - An iterable to populate the new tree.\n * @param [options] - Options for the new tree.\n * @returns A new AVLTree.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<AVLTreeOptions<TK, TV, TR>>\n ): AVLTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeOptions<TK, TV, TR>\n ) => AVLTree<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n /**\n * (Protected) Swaps properties of two nodes, including height.\n * @remarks Time O(H) (due to `ensureNode`), but O(1) if nodes are passed directly.\n *\n * @param srcNode - The source node.\n * @param destNode - The destination node.\n * @returns The `destNode` (now holding `srcNode`'s properties).\n */\n protected override _swapProperties(\n srcNode: BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>,\n destNode: BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>\n ): AVLTreeNode<K, V> | undefined {\n const srcNodeEnsured = this.ensureNode(srcNode);\n const destNodeEnsured = this.ensureNode(destNode);\n\n if (srcNodeEnsured && destNodeEnsured) {\n const { key, value, height } = destNodeEnsured;\n const tempNode = this.createNode(key, value);\n\n if (tempNode) {\n tempNode.height = height;\n\n // Copy src to dest\n destNodeEnsured.key = srcNodeEnsured.key;\n if (!this._isMapMode) destNodeEnsured.value = srcNodeEnsured.value;\n destNodeEnsured.height = srcNodeEnsured.height;\n\n // Copy temp (original dest) to src\n srcNodeEnsured.key = tempNode.key;\n if (!this._isMapMode) srcNodeEnsured.value = tempNode.value;\n srcNodeEnsured.height = tempNode.height;\n }\n\n return destNodeEnsured;\n }\n return undefined;\n }\n\n /**\n * (Protected) Calculates the balance factor (height(right) - height(left)).\n * @remarks Time O(1) (assumes heights are stored).\n *\n * @param node - The node to check.\n * @returns The balance factor (positive if right-heavy, negative if left-heavy).\n */\n protected _balanceFactor(node: AVLTreeNode<K, V>): number {\n const left = node.left ? (node.left as AVLTreeNode<K, V>).height : -1;\n const right = node.right ? (node.right as AVLTreeNode<K, V>).height : -1;\n return right - left;\n }\n\n /**\n * (Protected) Recalculates and updates the height of a node based on its children's heights.\n * @remarks Time O(1) (assumes children's heights are correct).\n *\n * @param node - The node to update.\n */\n protected _updateHeight(node: AVLTreeNode<K, V>): void {\n const leftHeight = node.left ? (node.left as AVLTreeNode<K, V>).height : -1;\n const rightHeight = node.right ? (node.right as AVLTreeNode<K, V>).height : -1;\n node.height = 1 + Math.max(leftHeight, rightHeight);\n }\n\n /**\n * (Protected) Performs a Left-Left (LL) rotation (a single right rotation).\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceLL(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.left; // The left child\n if (B !== null) A.parent = B;\n if (B && B.right) {\n B.right.parent = A;\n }\n if (B) B.parent = parentOfA;\n\n // Update parent's child pointer\n if (A === this.root) {\n if (B) this._setRoot(B);\n } else {\n if (parentOfA?.left === A) {\n parentOfA.left = B;\n } else {\n if (parentOfA) parentOfA.right = B;\n }\n }\n\n // Perform rotation\n if (B) {\n A.left = B.right;\n B.right = A;\n }\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n }\n\n /**\n * (Protected) Performs a Left-Right (LR) double rotation.\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceLR(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.left;\n let C = undefined;\n if (B) {\n C = B.right; // The \"middle\" node\n }\n if (A && C !== null) A.parent = C;\n if (B && C !== null) B.parent = C;\n\n if (C) {\n if (C.left) {\n if (B !== null) C.left.parent = B;\n }\n if (C.right) {\n C.right.parent = A;\n }\n C.parent = parentOfA;\n }\n\n // Update parent's child pointer\n if (A === this.root) {\n if (C) this._setRoot(C);\n } else {\n if (parentOfA) {\n if (parentOfA.left === A) {\n parentOfA.left = C;\n } else {\n parentOfA.right = C;\n }\n }\n }\n\n // Perform rotation\n if (C) {\n A.left = C.right;\n if (B) B.right = C.left;\n C.left = B;\n C.right = A;\n }\n\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n if (C) this._updateHeight(C);\n }\n\n /**\n * (Protected) Performs a Right-Right (RR) rotation (a single left rotation).\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceRR(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.right; // The right child\n if (B !== null) A.parent = B;\n if (B) {\n if (B.left) {\n B.left.parent = A;\n }\n B.parent = parentOfA;\n }\n\n // Update parent's child pointer\n if (A === this.root) {\n if (B) this._setRoot(B);\n } else {\n if (parentOfA) {\n if (parentOfA.left === A) {\n parentOfA.left = B;\n } else {\n parentOfA.right = B;\n }\n }\n }\n\n // Perform rotation\n if (B) {\n A.right = B.left;\n B.left = A;\n }\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n }\n\n /**\n * (Protected) Performs a Right-Left (RL) double rotation.\n * @remarks Time O(1), Space O(1)\n *\n * @param A - The unbalanced node (root of the unbalanced subtree).\n */\n protected _balanceRL(A: AVLTreeNode<K, V>): void {\n const parentOfA = A.parent;\n const B = A.right;\n let C = undefined;\n if (B) {\n C = B.left; // The \"middle\" node\n }\n\n if (C !== null) A.parent = C;\n if (B && C !== null) B.parent = C;\n\n if (C) {\n if (C.left) {\n C.left.parent = A;\n }\n if (C.right) {\n if (B !== null) C.right.parent = B;\n }\n C.parent = parentOfA;\n }\n\n // Update parent's child pointer\n if (A === this.root) {\n if (C) this._setRoot(C);\n } else {\n if (parentOfA) {\n if (parentOfA.left === A) {\n parentOfA.left = C;\n } else {\n parentOfA.right = C;\n }\n }\n }\n\n // Perform rotation\n if (C) A.right = C.left;\n if (B && C) B.left = C.right;\n if (C) C.left = A;\n if (C) C.right = B;\n\n this._updateHeight(A);\n if (B) this._updateHeight(B);\n if (C) this._updateHeight(C);\n }\n\n /**\n * (Protected) Traverses up the tree from the specified node, updating heights and performing rotations as needed.\n * @remarks Time O(log N) (O(H)), as it traverses the path to root. Space O(H) for the path array.\n *\n * @param node - The node to start balancing from (e.g., the newly inserted node or parent of the deleted node).\n */\n protected _balancePath(node: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined): void {\n // Get the path from the node to the root.\n node = this.ensureNode(node);\n const path = this.getPathToRoot(node, node => node, false);\n\n // Iterate up the path (from node to root)\n for (let i = 0; i < path.length; i++) {\n const A = path[i];\n if (A) {\n this._updateHeight(A);\n\n // Check the balance factor\n switch (this._balanceFactor(A)) {\n case -2: // Left-heavy\n if (A && A.left) {\n if (this._balanceFactor(A.left) <= 0) {\n // Left-Left case\n this._balanceLL(A);\n } else {\n // Left-Right case\n this._balanceLR(A);\n }\n }\n break;\n case +2: // Right-heavy\n if (A && A.right) {\n if (this._balanceFactor(A.right) >= 0) {\n // Right-Right case\n this._balanceRR(A);\n } else {\n // Right-Left case\n this._balanceRL(A);\n }\n }\n }\n }\n }\n }\n\n /**\n * (Protected) Replaces a node, ensuring height is copied.\n * @remarks Time O(1)\n *\n * @param oldNode - The node to be replaced.\n * @param newNode - The node to insert.\n * @returns The `newNode`.\n */\n protected override _replaceNode(oldNode: AVLTreeNode<K, V>, newNode: AVLTreeNode<K, V>): AVLTreeNode<K, V> {\n // When replacing a node (e.g., on duplicate key), preserve the height.\n newNode.height = oldNode.height;\n return super._replaceNode(oldNode, newNode);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n CRUD,\n EntryCallback,\n FamilyPosition,\n OptNode,\n RBTNColor,\n RedBlackTreeOptions\n} from '../../types';\nimport { BST } from './bst';\nimport { IBinaryTree } from '../../interfaces';\n\nexport class RedBlackTreeNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: RedBlackTreeNode<K, V> = undefined;\n\n /**\n * Create a Red-Black Tree and optionally bulk-insert items.\n * @remarks Time O(n log n), Space O(n)\n * @param key - See parameter type for details.\n * @param [value]- See parameter type for details.\n * @param color - See parameter type for details.\n * @returns New RedBlackTree instance.\n */\n\n constructor(key: K, value?: V, color: RBTNColor = 'BLACK') {\n this.key = key;\n this.value = value;\n this.color = color;\n }\n\n _left?: RedBlackTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n\n get left(): RedBlackTreeNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left node, or null/undefined.\n * @returns void\n */\n\n set left(v: RedBlackTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: RedBlackTreeNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n\n get right(): RedBlackTreeNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right node, or null/undefined.\n * @returns void\n */\n\n set right(v: RedBlackTreeNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Represents a Red-Black Tree (self-balancing BST) supporting map-like mode and stable O(log n) updates.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n * 1. Efficient self-balancing, but not completely balanced. Compared with AVLTree, the addition and deletion efficiency is high, but the query efficiency is slightly lower.\n * 2. It is BST itself. Compared with Heap which is not completely ordered, RedBlackTree is completely ordered.\n *\n * @example\n * // basic Red-Black Tree with simple number keys\n * // Create a simple Red-Black Tree with numeric keys\n * const tree = new RedBlackTree([5, 2, 8, 1, 9]);\n *\n * tree.print();\n * // _2___\n * // / \\\n * // 1 _8_\n * // / \\\n * // 5 9\n *\n * // Verify the tree maintains sorted order\n * console.log([...tree.keys()]); // [1, 2, 5, 8, 9];\n *\n * // Check size\n * console.log(tree.size); // 5;\n * @example\n * // Red-Black Tree with key-value pairs for lookups\n * interface Employee {\n * id: number;\n * name: string;\n * }\n *\n * // Create tree with employee data\n * const employees = new RedBlackTree<number, Employee>([\n * [1, { id: 1, name: 'Alice' }],\n * [3, { id: 3, name: 'Charlie' }],\n * [2, { id: 2, name: 'Bob' }]\n * ]);\n *\n * // Retrieve employee by ID\n * const alice = employees.get(1);\n * console.log(alice?.name); // 'Alice';\n *\n * // Verify sorted order by ID\n * console.log([...employees.keys()]); // [1, 2, 3];\n * @example\n * // Red-Black Tree range search for filtering\n * interface Product {\n * name: string;\n * price: number;\n * }\n *\n * const products = new RedBlackTree<number, Product>([\n * [10, { name: 'Item A', price: 10 }],\n * [25, { name: 'Item B', price: 25 }],\n * [40, { name: 'Item C', price: 40 }],\n * [50, { name: 'Item D', price: 50 }]\n * ]);\n *\n * // Find products in price range [20, 45]\n * const pricesInRange = products.rangeSearch([20, 45], node => {\n * return products.get(node)?.name;\n * });\n *\n * console.log(pricesInRange); // ['Item B', 'Item C'];\n * @example\n * // Red-Black Tree as database index for stock market data\n * interface StockPrice {\n * symbol: string;\n * volume: number;\n * timestamp: Date;\n * }\n *\n * // Simulate real-time stock price index\n * const priceIndex = new RedBlackTree<number, StockPrice>([\n * [142.5, { symbol: 'AAPL', volume: 1000000, timestamp: new Date() }],\n * [335.2, { symbol: 'MSFT', volume: 800000, timestamp: new Date() }],\n * [3285.04, { symbol: 'AMZN', volume: 500000, timestamp: new Date() }],\n * [267.98, { symbol: 'META', volume: 750000, timestamp: new Date() }],\n * [234.57, { symbol: 'GOOGL', volume: 900000, timestamp: new Date() }]\n * ]);\n *\n * // Find highest-priced stock\n * const maxPrice = priceIndex.getRightMost();\n * console.log(priceIndex.get(maxPrice)?.symbol); // 'AMZN';\n *\n * // Find stocks in price range [200, 400] for portfolio balancing\n * const stocksInRange = priceIndex.rangeSearch([200, 400], node => {\n * const stock = priceIndex.get(node);\n * return {\n * symbol: stock?.symbol,\n * price: node,\n * volume: stock?.volume\n * };\n * });\n *\n * console.log(stocksInRange.length); // 3;\n * console.log(stocksInRange.some((s: any) => s.symbol === 'GOOGL')); // true;\n * console.log(stocksInRange.some((s: any) => s.symbol === 'META')); // true;\n * console.log(stocksInRange.some((s: any) => s.symbol === 'MSFT')); // true;\n */\n\nexport class RedBlackTree<K = any, V = any, R = any> extends BST<K, V, R> implements IBinaryTree<K, V, R> {\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: RedBlackTreeOptions<K, V, R>\n ) {\n super([], options);\n\n this._root = this.NIL;\n\n if (keysNodesEntriesOrRaws) {\n this.addMany(keysNodesEntriesOrRaws);\n }\n }\n\n protected override _root: RedBlackTreeNode<K, V> | undefined;\n\n /**\n * Get the current root node.\n * @remarks Time O(1), Space O(1)\n * @returns Root node, or undefined.\n */\n override get root(): RedBlackTreeNode<K, V> | undefined {\n return this._root;\n }\n\n /**\n * Create a red-black node for the given key/value (value ignored in map mode).\n * @remarks Time O(1), Space O(1)\n * @param key - See parameter type for details.\n * @param [value] - See parameter type for details.\n * @param color - See parameter type for details.\n * @returns A new RedBlackTreeNode instance.\n */\n override createNode(key: K, value?: V, color: RBTNColor = 'BLACK'): RedBlackTreeNode<K, V> {\n return new RedBlackTreeNode<K, V>(key, this._isMapMode ? undefined : value, color);\n }\n\n /**\n * Type guard: check whether the input is a RedBlackTreeNode.\n * @remarks Time O(1), Space O(1)\n * @param keyNodeOrEntry - See parameter type for details.\n * @returns True if the value is a RedBlackTreeNode.\n */\n\n override isNode(\n keyNodeOrEntry: K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is RedBlackTreeNode<K, V> {\n return keyNodeOrEntry instanceof RedBlackTreeNode;\n }\n\n /**\n * Remove all nodes and clear the key→value store (if in map mode).\n * @remarks Time O(n), Space O(1)\n * @returns void\n */\n\n override clear() {\n super.clear();\n this._root = this.NIL;\n }\n\n /**\n * Insert or replace an entry using BST order and red-black fix-up.\n * @remarks Time O(log n), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.\n * @param [value]- See parameter type for details.\n * @returns True if inserted or updated; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);\n if (!this.isRealNode(newNode)) return false;\n\n const insertStatus = this._insert(newNode);\n\n if (insertStatus === 'CREATED') {\n if (this.isRealNode(this._root)) {\n this._root.color = 'BLACK';\n } else {\n return false;\n }\n if (this._isMapMode) this._setValue(newNode.key, newValue);\n this._size++;\n return true;\n }\n if (insertStatus === 'UPDATED') {\n if (this._isMapMode) this._setValue(newNode.key, newValue);\n return true;\n }\n return false;\n }\n\n /**\n * Delete a node by key/node/entry and rebalance as needed.\n * @remarks Time O(log n), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node to delete.\n * @returns Array with deletion metadata (removed node, rebalancing hint if any).\n */\n\n override delete(\n keyNodeOrEntry: K | RedBlackTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>[] {\n if (keyNodeOrEntry === null) return [];\n\n const results: BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>[] = [];\n let nodeToDelete: OptNode<RedBlackTreeNode<K, V>>;\n if (this._isPredicate(keyNodeOrEntry)) nodeToDelete = this.getNode(keyNodeOrEntry);\n else nodeToDelete = this.isRealNode(keyNodeOrEntry) ? keyNodeOrEntry : this.getNode(keyNodeOrEntry);\n\n if (!nodeToDelete) {\n return results;\n }\n\n let originalColor = nodeToDelete.color;\n let replacementNode: RedBlackTreeNode<K, V> | undefined;\n\n if (!this.isRealNode(nodeToDelete.left)) {\n if (nodeToDelete.right !== null) {\n replacementNode = nodeToDelete.right;\n this._transplant(nodeToDelete, nodeToDelete.right);\n }\n } else if (!this.isRealNode(nodeToDelete.right)) {\n replacementNode = nodeToDelete.left;\n this._transplant(nodeToDelete, nodeToDelete.left);\n } else {\n const successor = this.getLeftMost(node => node, nodeToDelete.right);\n if (successor) {\n originalColor = successor.color;\n if (successor.right !== null) replacementNode = successor.right;\n\n if (successor.parent === nodeToDelete) {\n if (this.isRealNode(replacementNode)) {\n replacementNode.parent = successor;\n }\n } else {\n if (successor.right !== null) {\n this._transplant(successor, successor.right);\n successor.right = nodeToDelete.right;\n }\n if (this.isRealNode(successor.right)) {\n successor.right.parent = successor;\n }\n }\n\n this._transplant(nodeToDelete, successor);\n successor.left = nodeToDelete.left;\n if (this.isRealNode(successor.left)) {\n successor.left.parent = successor;\n }\n successor.color = nodeToDelete.color;\n }\n }\n if (this._isMapMode) this._store.delete(nodeToDelete.key);\n this._size--;\n\n if (originalColor === 'BLACK') {\n this._deleteFixup(replacementNode);\n }\n\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n\n return results;\n }\n\n /**\n * Transform entries into a like-kind red-black tree with possibly different key/value types.\n * @remarks Time O(n), Space O(n)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Mapping function from (key, value, index, tree) to a new [key, value].\n * @param [options] - See parameter type for details.\n * @param [thisArg] - See parameter type for details.\n * @returns A new RedBlackTree with mapped entries.\n */\n\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<RedBlackTreeOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): RedBlackTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<RedBlackTreeOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: RedBlackTreeOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<\n TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n > = [],\n options?: Partial<RedBlackTreeOptions<TK, TV, TR>>\n ): RedBlackTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: RedBlackTreeOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n protected override _setRoot(v: RedBlackTreeNode<K, V> | undefined) {\n if (v) {\n v.parent = undefined;\n }\n this._root = v;\n }\n\n protected override _replaceNode(\n oldNode: RedBlackTreeNode<K, V>,\n newNode: RedBlackTreeNode<K, V>\n ): RedBlackTreeNode<K, V> {\n newNode.color = oldNode.color;\n\n return super._replaceNode(oldNode, newNode);\n }\n\n /**\n * (Protected) Standard BST insert followed by red-black fix-up.\n * @remarks Time O(log n), Space O(1)\n * @param node - Node to insert.\n * @returns Status string: 'CREATED' or 'UPDATED'.\n */\n\n protected _insert(node: RedBlackTreeNode<K, V>): CRUD {\n let current = this.root ?? this.NIL;\n let parent: RedBlackTreeNode<K, V> | undefined = undefined;\n\n while (current !== this.NIL) {\n parent = current;\n const compared = this._compare(node.key, current.key);\n if (compared < 0) {\n current = current.left ?? this.NIL;\n } else if (compared > 0) {\n current = current.right ?? this.NIL;\n } else {\n this._replaceNode(current, node);\n return 'UPDATED';\n }\n }\n\n node.parent = parent;\n\n if (!parent) {\n this._setRoot(node);\n } else if (this._compare(node.key, parent.key) < 0) {\n parent.left = node;\n } else {\n parent.right = node;\n }\n\n node.left = this.NIL;\n node.right = this.NIL;\n node.color = 'RED';\n\n this._insertFixup(node);\n return 'CREATED';\n }\n\n /**\n * (Protected) Transplant a subtree in place of another during deletion.\n * @remarks Time O(1), Space O(1)\n * @param u - Node to replace.\n * @param v - Replacement subtree root (may be undefined).\n * @returns void\n */\n\n protected _transplant(u: RedBlackTreeNode<K, V>, v: RedBlackTreeNode<K, V> | undefined): void {\n if (!u.parent) {\n this._setRoot(v);\n } else if (u === u.parent.left) {\n u.parent.left = v;\n } else {\n u.parent.right = v;\n }\n\n if (v) {\n v.parent = u.parent;\n }\n }\n\n /**\n * (Protected) Restore red-black properties after insertion (recolor/rotate).\n * @remarks Time O(log n), Space O(1)\n * @param z - Recently inserted node.\n * @returns void\n */\n\n protected _insertFixup(z: RedBlackTreeNode<K, V> | undefined): void {\n while (z?.parent?.color === 'RED') {\n if (z.parent === z.parent.parent?.left) {\n const y = z.parent.parent.right;\n if (y?.color === 'RED') {\n z.parent.color = 'BLACK';\n y.color = 'BLACK';\n z.parent.parent.color = 'RED';\n\n z = z.parent.parent;\n } else {\n if (z === z.parent.right) {\n z = z.parent;\n this._leftRotate(z);\n }\n\n if (z && z.parent && z.parent.parent) {\n z.parent.color = 'BLACK';\n z.parent.parent.color = 'RED';\n this._rightRotate(z.parent.parent);\n }\n }\n } else {\n const y: RedBlackTreeNode<K, V> | undefined = z?.parent?.parent?.left ?? undefined;\n if (y?.color === 'RED') {\n z.parent.color = 'BLACK';\n y.color = 'BLACK';\n z.parent.parent!.color = 'RED';\n z = z.parent.parent;\n } else {\n if (z === z.parent.left) {\n z = z.parent;\n this._rightRotate(z);\n }\n\n if (z && z.parent && z.parent.parent) {\n z.parent.color = 'BLACK';\n z.parent.parent.color = 'RED';\n this._leftRotate(z.parent.parent);\n }\n }\n }\n }\n\n if (this.isRealNode(this._root)) this._root.color = 'BLACK';\n }\n\n /**\n * (Protected) Restore red-black properties after deletion (recolor/rotate).\n * @remarks Time O(log n), Space O(1)\n * @param node - Child that replaced the deleted node (may be undefined).\n * @returns void\n */\n\n protected _deleteFixup(node: RedBlackTreeNode<K, V> | undefined): void {\n if (!node || node === this.root || node.color === 'BLACK') {\n if (node) {\n node.color = 'BLACK';\n }\n return;\n }\n\n while (node && node !== this.root && node.color === 'BLACK') {\n const parent: RedBlackTreeNode<K, V> | undefined = node.parent;\n\n if (!parent) {\n break;\n }\n\n if (node === parent.left) {\n let sibling = parent.right;\n\n if (sibling?.color === 'RED') {\n sibling.color = 'BLACK';\n parent.color = 'RED';\n this._leftRotate(parent);\n sibling = parent.right;\n }\n\n if ((sibling?.left?.color ?? 'BLACK') === 'BLACK') {\n if (sibling) sibling.color = 'RED';\n node = parent;\n } else {\n if (sibling?.left) sibling.left.color = 'BLACK';\n if (sibling) sibling.color = parent.color;\n parent.color = 'BLACK';\n this._rightRotate(parent);\n node = this.root;\n }\n } else {\n let sibling = parent.left;\n\n if (sibling?.color === 'RED') {\n sibling.color = 'BLACK';\n if (parent) parent.color = 'RED';\n this._rightRotate(parent);\n if (parent) sibling = parent.left;\n }\n\n if ((sibling?.right?.color ?? 'BLACK') === 'BLACK') {\n if (sibling) sibling.color = 'RED';\n node = parent;\n } else {\n if (sibling?.right) sibling.right.color = 'BLACK';\n if (sibling) sibling.color = parent.color;\n if (parent) parent.color = 'BLACK';\n this._leftRotate(parent);\n node = this.root;\n }\n }\n }\n\n if (node) {\n node.color = 'BLACK';\n }\n }\n\n /**\n * (Protected) Perform a left rotation around x.\n * @remarks Time O(1), Space O(1)\n * @param x - Pivot node to rotate around.\n * @returns void\n */\n\n protected _leftRotate(x: RedBlackTreeNode<K, V> | undefined): void {\n if (!x || !x.right) {\n return;\n }\n\n const y = x.right;\n x.right = y.left;\n\n if (y.left && y.left !== this.NIL) {\n y.left.parent = x;\n }\n\n y.parent = x.parent;\n\n if (!x.parent) {\n this._setRoot(y);\n } else if (x === x.parent.left) {\n x.parent.left = y;\n } else {\n x.parent.right = y;\n }\n\n y.left = x;\n x.parent = y;\n }\n\n /**\n * (Protected) Perform a right rotation around y.\n * @remarks Time O(1), Space O(1)\n * @param y - Pivot node to rotate around.\n * @returns void\n */\n\n protected _rightRotate(y: RedBlackTreeNode<K, V> | undefined): void {\n if (!y || !y.left) {\n return;\n }\n\n const x = y.left;\n y.left = x.right;\n\n if (x.right && x.right !== this.NIL) {\n x.right.parent = y;\n }\n\n x.parent = y.parent;\n\n if (!y.parent) {\n this._setRoot(x);\n } else if (y === y.parent.left) {\n y.parent.left = x;\n } else {\n y.parent.right = x;\n }\n\n x.right = y;\n y.parent = x;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n AVLTreeMultiMapOptions,\n BTNOptKeyOrNull,\n ElemOf,\n EntryCallback,\n FamilyPosition,\n IterationType,\n RBTNColor\n} from '../../types';\nimport { AVLTree, AVLTreeNode } from './avl-tree';\nimport { IBinaryTree } from '../../interfaces';\n\n/**\n * Node used by AVLTreeMultiMap; stores the key with a bucket of values (array).\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class AVLTreeMultiMapNode<K = any, V = any> {\n key: K;\n value?: V[];\n parent?: AVLTreeMultiMapNode<K, V> = undefined;\n\n /**\n * Create an AVLTreeMultiMap node with a value bucket.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param value - Initial array of values.\n * @returns New AVLTreeMultiMapNode instance.\n */\n constructor(key: K, value: V[] = []) {\n this.key = key;\n this.value = value;\n }\n\n _left?: AVLTreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): AVLTreeMultiMapNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: AVLTreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: AVLTreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): AVLTreeMultiMapNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: AVLTreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * AVL-tree–based multimap (key → array of values). Preserves O(log N) updates and supports map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n */\nexport class AVLTreeMultiMap<K = any, V = any, R = any> extends AVLTree<K, V[], R> implements IBinaryTree<K, V[], R> {\n /**\n * Create an AVLTreeMultiMap and optionally bulk-insert items.\n * @remarks Time O(N log N), Space O(N)\n * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.\n * @param [options] - Options for AVLTreeMultiMap (comparator, reverse, map mode).\n * @returns New AVLTreeMultiMap instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined | R\n > = [],\n options?: AVLTreeMultiMapOptions<K, V[], R>\n ) {\n super([], { ...options, isMapMode: true });\n if (keysNodesEntriesOrRaws) {\n this.addMany(keysNodesEntriesOrRaws);\n }\n }\n\n override createNode(key: K, value: V[] = []): AVLTreeMultiMapNode<K, V> {\n return new AVLTreeMultiMapNode<K, V>(key, this._isMapMode ? [] : value);\n }\n\n /**\n * Checks if the given item is a `AVLTreeMultiMapNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a AVLTreeMultiMapNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): keyNodeOrEntry is AVLTreeMultiMapNode<K, V> {\n return keyNodeOrEntry instanceof AVLTreeMultiMapNode;\n }\n\n override add(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): boolean;\n\n override add(key: K, value: V): boolean;\n\n /**\n * Insert a value or a list of values into the multimap. If the key exists, values are appended.\n * @remarks Time O(log N + M), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry.\n * @param [value] - Single value to add when a bare key is provided.\n * @returns True if inserted or appended; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value?: V\n ): boolean {\n if (this.isRealNode(keyNodeOrEntry)) return super.add(keyNodeOrEntry);\n\n const _commonAdd = (key?: BTNOptKeyOrNull<K>, values?: V[]) => {\n if (key === undefined || key === null) return false;\n\n const _addToValues = () => {\n const existingValues = this.get(key);\n if (existingValues !== undefined && values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n }\n return false;\n };\n\n const _addByNode = () => {\n const existingNode = this.getNode(key);\n if (this.isRealNode(existingNode)) {\n const existingValues = this.get(existingNode);\n if (existingValues === undefined) {\n super.add(key, values);\n return true;\n }\n if (values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n } else {\n return false;\n }\n } else {\n return super.add(key, values);\n }\n };\n\n if (this._isMapMode) {\n return _addByNode() || _addToValues();\n }\n return _addToValues() || _addByNode();\n };\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, values] = keyNodeOrEntry;\n return _commonAdd(key, value !== undefined ? [value] : values);\n }\n\n return _commonAdd(keyNodeOrEntry, value !== undefined ? [value] : undefined);\n }\n\n /**\n * Delete a single value from the bucket at a given key. Removes the key if the bucket becomes empty.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry to locate the bucket.\n * @param value - Value to remove from the bucket.\n * @returns True if the value was removed; false if not found.\n */\n deleteValue(\n keyNodeOrEntry: K | AVLTreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value: V\n ): boolean {\n const values = this.get(keyNodeOrEntry);\n if (Array.isArray(values)) {\n const index = values.indexOf(value);\n if (index === -1) return false;\n values.splice(index, 1);\n\n if (values.length === 0) this.delete(keyNodeOrEntry);\n\n return true;\n }\n return false;\n }\n\n /**\n * Rebuild the tree into a perfectly balanced form using in-order nodes.\n * @remarks Time O(N), Space O(N)\n * @param [iterationType] - Traversal style to use when constructing the balanced tree.\n * @returns True if rebalancing succeeded (tree not empty).\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n === 0) return false;\n\n this._clearNodes();\n\n const build = (l: number, r: number, parent?: any): any | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m];\n root.left = build(l, m - 1, root);\n root.right = build(m + 1, r, root);\n root.parent = parent;\n const lh = root.left ? root.left.height : -1;\n const rh = root.right ? root.right.height : -1;\n root.height = Math.max(lh, rh) + 1;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n return true;\n }\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MVArr\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new AVLTreeMultiMap when mapping to array values; see overloads.\n */\n override map<MK = K, MVArr extends unknown[] = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MVArr]>,\n options?: Partial<AVLTreeMultiMapOptions<MK, MVArr, MR>>,\n thisArg?: unknown\n ): AVLTreeMultiMap<MK, ElemOf<MVArr>, MR>;\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new AVLTree when mapping to non-array values; see overloads.\n */\n override map<MK = K, MV = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<AVLTreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTree<MK, MV, MR>;\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns The mapped AVLTree or AVLTreeMultiMap depending on MV; see overloads.\n */\n override map<MK, MV, MR extends object>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<AVLTreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let i = 0;\n for (const [k, v] of this) out.add(callback.call(thisArg, v, k, i++, this));\n return out;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(\n options?: Partial<AVLTreeMultiMapOptions<TK, TV, TR>>\n ): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeMultiMapOptions<TK, TV, TR>\n ) => AVLTree<TK, TV, TR>;\n return new Ctor([], { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind AVLTree built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<AVLTreeMultiMapOptions<TK, TV, TR>>\n ): AVLTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | AVLTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: AVLTreeMultiMapOptions<TK, TV, TR>\n ) => AVLTree<TK, TV, TR>;\n return new Ctor(iter, { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) });\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BTNOptKeyOrNull,\n ElemOf,\n EntryCallback,\n FamilyPosition,\n RBTNColor,\n TreeMultiMapOptions\n} from '../../types';\nimport { RedBlackTree, RedBlackTreeNode } from './red-black-tree';\nimport { IBinaryTree } from '../../interfaces';\n\n/**\n * Node used by TreeMultiMap; stores the key with a bucket of values (array).\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class TreeMultiMapNode<K = any, V = any> {\n key: K;\n value?: V[];\n parent?: TreeMultiMapNode<K, V> = undefined;\n\n /**\n * Create a TreeMultiMap node with an optional value bucket.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param [value] - Initial array of values.\n * @returns New TreeMultiMapNode instance.\n */\n constructor(key: K, value: V[] = [], color: RBTNColor = 'BLACK') {\n this.key = key;\n this.value = value;\n this.color = color;\n }\n\n _left?: TreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): TreeMultiMapNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: TreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: TreeMultiMapNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): TreeMultiMapNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: TreeMultiMapNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Red-Black Tree–based multimap (key → array of values). Preserves O(log N) updates and supports map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n *\n * @example\n * // players ranked by score with their equipment\n * type Equipment = {\n * name: string; // Equipment name\n * quality: 'legendary' | 'epic' | 'rare' | 'common';\n * level: number;\n * };\n *\n * type Player = {\n * name: string;\n * score: number;\n * equipments: Equipment[];\n * };\n *\n * // Mock player data with their scores and equipment\n * const players: Player[] = [\n * {\n * name: 'DragonSlayer',\n * score: 8750,\n * equipments: [\n * { name: 'AWM', quality: 'legendary', level: 85 },\n * { name: 'Level 3 Helmet', quality: 'epic', level: 80 },\n * { name: 'Extended Quickdraw Mag', quality: 'rare', level: 75 },\n * { name: 'Compensator', quality: 'epic', level: 78 },\n * { name: 'Vertical Grip', quality: 'rare', level: 72 }\n * ]\n * },\n * {\n * name: 'ShadowNinja',\n * score: 7200,\n * equipments: [\n * { name: 'M416', quality: 'epic', level: 75 },\n * { name: 'Ghillie Suit', quality: 'rare', level: 70 },\n * { name: 'Red Dot Sight', quality: 'common', level: 65 },\n * { name: 'Extended QuickDraw Mag', quality: 'rare', level: 68 }\n * ]\n * },\n * {\n * name: 'RuneMaster',\n * score: 9100,\n * equipments: [\n * { name: 'KAR98K', quality: 'legendary', level: 90 },\n * { name: 'Level 3 Vest', quality: 'legendary', level: 85 },\n * { name: 'Holographic Sight', quality: 'epic', level: 82 },\n * { name: 'Suppressor', quality: 'legendary', level: 88 },\n * { name: 'Level 3 Backpack', quality: 'epic', level: 80 }\n * ]\n * },\n * {\n * name: 'BattleKing',\n * score: 8500,\n * equipments: [\n * { name: 'AUG', quality: 'epic', level: 82 },\n * { name: 'Red Dot Sight', quality: 'rare', level: 75 },\n * { name: 'Extended Mag', quality: 'common', level: 70 },\n * { name: 'Tactical Stock', quality: 'rare', level: 76 }\n * ]\n * },\n * {\n * name: 'SniperElite',\n * score: 7800,\n * equipments: [\n * { name: 'M24', quality: 'legendary', level: 88 },\n * { name: 'Compensator', quality: 'epic', level: 80 },\n * { name: 'Scope 8x', quality: 'legendary', level: 85 },\n * { name: 'Level 2 Helmet', quality: 'rare', level: 75 }\n * ]\n * },\n * {\n * name: 'RushMaster',\n * score: 7500,\n * equipments: [\n * { name: 'Vector', quality: 'rare', level: 72 },\n * { name: 'Level 2 Helmet', quality: 'common', level: 65 },\n * { name: 'Quickdraw Mag', quality: 'common', level: 60 },\n * { name: 'Laser Sight', quality: 'rare', level: 68 }\n * ]\n * },\n * {\n * name: 'GhostWarrior',\n * score: 8200,\n * equipments: [\n * { name: 'SCAR-L', quality: 'epic', level: 78 },\n * { name: 'Extended Quickdraw Mag', quality: 'rare', level: 70 },\n * { name: 'Holographic Sight', quality: 'epic', level: 75 },\n * { name: 'Suppressor', quality: 'rare', level: 72 },\n * { name: 'Vertical Grip', quality: 'common', level: 65 }\n * ]\n * },\n * {\n * name: 'DeathDealer',\n * score: 7300,\n * equipments: [\n * { name: 'SKS', quality: 'epic', level: 76 },\n * { name: 'Holographic Sight', quality: 'rare', level: 68 },\n * { name: 'Extended Mag', quality: 'common', level: 65 }\n * ]\n * },\n * {\n * name: 'StormRider',\n * score: 8900,\n * equipments: [\n * { name: 'MK14', quality: 'legendary', level: 92 },\n * { name: 'Level 3 Backpack', quality: 'legendary', level: 85 },\n * { name: 'Scope 8x', quality: 'epic', level: 80 },\n * { name: 'Suppressor', quality: 'legendary', level: 88 },\n * { name: 'Tactical Stock', quality: 'rare', level: 75 }\n * ]\n * },\n * {\n * name: 'CombatLegend',\n * score: 7600,\n * equipments: [\n * { name: 'UMP45', quality: 'rare', level: 74 },\n * { name: 'Level 2 Vest', quality: 'common', level: 67 },\n * { name: 'Red Dot Sight', quality: 'common', level: 62 },\n * { name: 'Extended Mag', quality: 'rare', level: 70 }\n * ]\n * }\n * ];\n *\n * // Create a TreeMultiMap for player rankings\n * const playerRankings = new TreeMultiMap<number, Equipment, Player>(players, {\n * toEntryFn: ({ score, equipments }) => [score, equipments],\n * isMapMode: false\n * });\n *\n * const topPlayersEquipments = playerRankings.rangeSearch([8900, 10000], node => playerRankings.get(node));\n * console.log(topPlayersEquipments); // [\n * // [\n * // {\n * // name: 'MK14',\n * // quality: 'legendary',\n * // level: 92\n * // },\n * // { name: 'Level 3 Backpack', quality: 'legendary', level: 85 },\n * // {\n * // name: 'Scope 8x',\n * // quality: 'epic',\n * // level: 80\n * // },\n * // { name: 'Suppressor', quality: 'legendary', level: 88 },\n * // {\n * // name: 'Tactical Stock',\n * // quality: 'rare',\n * // level: 75\n * // }\n * // ],\n * // [\n * // { name: 'KAR98K', quality: 'legendary', level: 90 },\n * // {\n * // name: 'Level 3 Vest',\n * // quality: 'legendary',\n * // level: 85\n * // },\n * // { name: 'Holographic Sight', quality: 'epic', level: 82 },\n * // {\n * // name: 'Suppressor',\n * // quality: 'legendary',\n * // level: 88\n * // },\n * // { name: 'Level 3 Backpack', quality: 'epic', level: 80 }\n * // ]\n * // ];\n */\nexport class TreeMultiMap<K = any, V = any, R = any> extends RedBlackTree<K, V[], R> implements IBinaryTree<K, V[], R> {\n /**\n * Create a TreeMultiMap and optionally bulk-insert items.\n * @remarks Time O(N log N), Space O(N)\n * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.\n * @param [options] - Options for TreeMultiMap (comparator, reverse, map mode).\n * @returns New TreeMultiMap instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined | R\n > = [],\n options?: TreeMultiMapOptions<K, V[], R>\n ) {\n super([], { ...options });\n if (keysNodesEntriesOrRaws) {\n this.addMany(keysNodesEntriesOrRaws);\n }\n }\n\n override createNode(key: K, value: V[] = []): TreeMultiMapNode<K, V> {\n return new TreeMultiMapNode<K, V>(key, this._isMapMode ? [] : value);\n }\n\n /**\n * Checks if the given item is a `TreeMultiMapNode` instance.\n * @remarks Time O(1), Space O(1)\n *\n * @param keyNodeOrEntry - The item to check.\n * @returns True if it's a TreeMultiMapNode, false otherwise.\n */\n override isNode(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): keyNodeOrEntry is TreeMultiMapNode<K, V> {\n return keyNodeOrEntry instanceof TreeMultiMapNode;\n }\n\n override add(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined\n ): boolean;\n\n override add(key: K, value: V): boolean;\n\n /**\n * Insert a value or a list of values into the multimap. If the key exists, values are appended.\n * @remarks Time O(log N + M), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry.\n * @param [value] - Single value to add when a bare key is provided.\n * @returns True if inserted or appended; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value?: V\n ): boolean {\n if (this.isRealNode(keyNodeOrEntry)) return super.add(keyNodeOrEntry);\n\n const _commonAdd = (key?: BTNOptKeyOrNull<K>, values?: V[]) => {\n if (key === undefined || key === null) return false;\n\n const _addToValues = () => {\n const existingValues = this.get(key);\n if (existingValues !== undefined && values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n }\n return false;\n };\n\n const _addByNode = () => {\n const existingNode = this.getNode(key);\n if (this.isRealNode(existingNode)) {\n const existingValues = this.get(existingNode);\n if (existingValues === undefined) {\n super.add(key, values);\n return true;\n }\n if (values !== undefined) {\n for (const value of values) existingValues.push(value);\n return true;\n } else {\n return false;\n }\n } else {\n return super.add(key, values);\n }\n };\n\n if (this._isMapMode) {\n return _addByNode() || _addToValues();\n }\n return _addToValues() || _addByNode();\n };\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, values] = keyNodeOrEntry;\n return _commonAdd(key, value !== undefined ? [value] : values);\n }\n\n return _commonAdd(keyNodeOrEntry, value !== undefined ? [value] : undefined);\n }\n\n /**\n * Delete a single value from the bucket at a given key. Removes the key if the bucket becomes empty.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, values] entry to locate the bucket.\n * @param value - Value to remove from the bucket.\n * @returns True if the value was removed; false if not found.\n */\n deleteValue(\n keyNodeOrEntry: K | TreeMultiMapNode<K, V> | [K | null | undefined, V[] | undefined] | null | undefined,\n value: V\n ): boolean {\n const values = this.get(keyNodeOrEntry);\n if (Array.isArray(values)) {\n const index = values.indexOf(value);\n if (index === -1) return false;\n values.splice(index, 1);\n\n if (values.length === 0) this.delete(keyNodeOrEntry);\n\n return true;\n }\n return false;\n }\n\n override map<MK = K, MVArr extends unknown[] = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MVArr]>,\n options?: Partial<TreeMultiMapOptions<MK, MVArr, MR>>,\n thisArg?: unknown\n ): TreeMultiMap<MK, ElemOf<MVArr>, MR>;\n\n override map<MK = K, MV = V[], MR = any>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<TreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): RedBlackTree<MK, MV, MR>;\n\n /**\n * Create a new tree by mapping each [key, values] bucket.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, values, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new RedBlackTree (or TreeMultiMap when mapping to array values; see overloads).\n */\n override map<MK, MV, MR extends object>(\n callback: EntryCallback<K, V[] | undefined, [MK, MV]>,\n options?: Partial<TreeMultiMapOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): RedBlackTree<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n let i = 0;\n for (const [k, v] of this) out.add(callback.call(thisArg, v, k, i++, this));\n return out;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<TreeMultiMapOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeMultiMapOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor([], { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind RedBlackTree built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<\n TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n > = [],\n options?: Partial<TreeMultiMapOptions<TK, TV, TR>>\n ): RedBlackTree<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | RedBlackTreeNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeMultiMapOptions<TK, TV, TR>\n ) => RedBlackTree<TK, TV, TR>;\n return new Ctor(iter, { ...(this._snapshotOptions?.<TK, TV, TR>() ?? {}), ...(options ?? {}) });\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n BinaryTreeDeleteResult,\n BSTNOptKeyOrNode,\n EntryCallback,\n FamilyPosition,\n IterationType,\n OptNode,\n RBTNColor,\n TreeCounterOptions\n} from '../../types';\nimport { BSTNode } from './bst';\nimport { IBinaryTree } from '../../interfaces';\nimport { RedBlackTree } from './red-black-tree';\n\n/**\n * RB-tree node with an extra 'count' field; keeps parent/child links.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class TreeCounterNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: TreeCounterNode<K, V> = undefined;\n\n /**\n * Create a tree counter node.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param [value] - Value associated with the key (ignored in map mode).\n * @param [count] - Initial count for this node (default 1).\n * @param color - Initial color ('RED' or 'BLACK').\n * @returns New TreeCounterNode instance.\n */\n constructor(key: K, value?: V, count = 1, color: RBTNColor = 'BLACK') {\n this.key = key;\n this.value = value;\n this.color = color;\n this.count = count;\n }\n\n _left?: TreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): TreeCounterNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: TreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: TreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): TreeCounterNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: TreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * Red-Black Tree–based counter map (key → value with per-node count). Supports O(log N) updates and map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n */\nexport class TreeCounter<K = any, V = any, R = any> extends RedBlackTree<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Create a TreeCounter and optionally bulk-insert items.\n * @remarks Time O(N log N), Space O(N)\n * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.\n * @param [options] - Options for TreeCounter (comparator, reverse, map mode).\n * @returns New TreeCounter instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: TreeCounterOptions<K, V, R>\n ) {\n super([], options);\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected _count = 0;\n\n /**\n * Get the total aggregate count across all nodes.\n * @remarks Time O(1), Space O(1)\n * @returns Total count.\n */\n\n get count(): number {\n return this._count;\n }\n\n /**\n * Compute the total count by traversing the tree (sums node.count).\n * @remarks Time O(N), Space O(H)\n * @returns Total count recomputed from nodes.\n */\n\n getComputedCount(): number {\n let sum = 0;\n this.dfs(node => (sum += node ? node.count : 0));\n return sum;\n }\n\n override createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): TreeCounterNode<K, V> {\n return new TreeCounterNode(key, this._isMapMode ? undefined : value, count, color) as TreeCounterNode<K, V>;\n }\n\n /**\n * Type guard: check whether the input is a TreeCounterNode.\n * @remarks Time O(1), Space O(1)\n * @returns True if the value is a TreeCounterNode.\n */\n\n override isNode(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is TreeCounterNode<K, V> {\n return keyNodeOrEntry instanceof TreeCounterNode;\n }\n\n /**\n * Insert or increment a node and update aggregate count.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.\n * @param [value] - Value when a bare key is provided (ignored in map mode).\n * @param [count] - How much to increase the node's count (default 1).\n * @returns True if inserted/updated; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value, count);\n const orgCount = newNode?.count || 0;\n const isSuccessAdded = super.add(newNode, newValue);\n if (isSuccessAdded) {\n this._count += orgCount;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Delete a node (or decrement its count) and rebalance if needed.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node.\n * @param [ignoreCount] - If true, remove the node regardless of its count.\n * @returns Array of deletion results including deleted node and a rebalance hint when present.\n */\n override delete(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n ignoreCount = false\n ): BinaryTreeDeleteResult<TreeCounterNode<K, V>>[] {\n if (keyNodeOrEntry === null) return [];\n\n const results: BinaryTreeDeleteResult<TreeCounterNode<K, V>>[] = [];\n\n let nodeToDelete: OptNode<TreeCounterNode<K, V>>;\n if (this._isPredicate(keyNodeOrEntry)) nodeToDelete = this.getNode(keyNodeOrEntry);\n else nodeToDelete = this.isRealNode(keyNodeOrEntry) ? keyNodeOrEntry : this.getNode(keyNodeOrEntry);\n if (!nodeToDelete) {\n return results;\n }\n\n let originalColor = nodeToDelete.color;\n let replacementNode: TreeCounterNode<K, V> | undefined;\n\n if (!this.isRealNode(nodeToDelete.left)) {\n if (nodeToDelete.right !== null) replacementNode = nodeToDelete.right;\n if (ignoreCount || nodeToDelete.count <= 1) {\n if (nodeToDelete.right !== null) {\n this._transplant(nodeToDelete, nodeToDelete.right);\n this._count -= nodeToDelete.count;\n }\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n } else if (!this.isRealNode(nodeToDelete.right)) {\n replacementNode = nodeToDelete.left;\n if (ignoreCount || nodeToDelete.count <= 1) {\n this._transplant(nodeToDelete, nodeToDelete.left);\n this._count -= nodeToDelete.count;\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n } else {\n const successor = this.getLeftMost(node => node, nodeToDelete.right);\n if (successor) {\n originalColor = successor.color;\n if (successor.right !== null) replacementNode = successor.right;\n if (successor.parent === nodeToDelete) {\n if (this.isRealNode(replacementNode)) {\n replacementNode.parent = successor;\n }\n } else {\n if (ignoreCount || nodeToDelete.count <= 1) {\n if (successor.right !== null) {\n this._transplant(successor, successor.right);\n this._count -= nodeToDelete.count;\n }\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n successor.right = nodeToDelete.right;\n if (this.isRealNode(successor.right)) {\n successor.right.parent = successor;\n }\n }\n if (ignoreCount || nodeToDelete.count <= 1) {\n this._transplant(nodeToDelete, successor);\n this._count -= nodeToDelete.count;\n } else {\n nodeToDelete.count--;\n this._count--;\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n return results;\n }\n successor.left = nodeToDelete.left;\n if (this.isRealNode(successor.left)) {\n successor.left.parent = successor;\n }\n successor.color = nodeToDelete.color;\n }\n }\n this._size--;\n if (originalColor === 'BLACK') {\n this._deleteFixup(replacementNode);\n }\n\n results.push({ deleted: nodeToDelete, needBalanced: undefined });\n\n return results;\n }\n\n /**\n * Remove all nodes and reset aggregate counters.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n override clear() {\n super.clear();\n this._count = 0;\n }\n\n /**\n * Rebuild the tree into a perfectly balanced form using in-order nodes.\n * @remarks Time O(N), Space O(N)\n * @param [iterationType] - Traversal style to use when constructing the balanced tree.\n * @returns True if rebalancing succeeded (tree not empty).\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n < 1) return false;\n\n let total = 0;\n for (const nd of nodes) total += nd ? nd.count : 0;\n\n this._clearNodes();\n\n const build = (l: number, r: number, parent?: TreeCounterNode<K, V>): TreeCounterNode<K, V> | undefined => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m]! as TreeCounterNode<K, V>;\n const leftChild = build(l, m - 1, root);\n const rightChild = build(m + 1, r, root);\n root.left = leftChild;\n root.right = rightChild;\n root.parent = parent;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n this._count = total;\n return true;\n }\n\n /**\n * Create a new TreeCounter by mapping each [key, value] entry.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, value, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new TreeCounter with mapped entries.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<TreeCounterOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): TreeCounter<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * Deep copy this tree, preserving map mode and aggregate counts.\n * @remarks Time O(N), Space O(N)\n * @returns A deep copy of this tree.\n */\n override clone(): this {\n const out = this._createInstance<K, V, R>();\n this._clone(out as unknown as any);\n (out as any)._count = (this as any)._count;\n return out as unknown as this;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(options?: Partial<TreeCounterOptions<TK, TV, TR>>): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeCounterOptions<TK, TV, TR>\n ) => this;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind TreeCounter built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],\n options?: Partial<TreeCounterOptions<TK, TV, TR>>\n ): TreeCounter<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,\n opts?: TreeCounterOptions<TK, TV, TR>\n ) => TreeCounter<TK, TV, TR>;\n return new Ctor(iter as unknown as Iterable<TK | any>, {\n ...this._snapshotOptions<TK, TV, TR>(),\n ...(options ?? {})\n });\n }\n\n /**\n * (Protected) Normalize input into a node plus its effective value and count.\n * @remarks Time O(1), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry.\n * @param [value] - Value used when a bare key is provided.\n * @param [count] - Count increment to apply (default 1).\n * @returns Tuple [node, value] where node may be undefined.\n */\n protected override _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): [TreeCounterNode<K, V> | undefined, V | undefined] {\n if (keyNodeOrEntry === undefined || keyNodeOrEntry === null) return [undefined, undefined];\n\n if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, entryValue] = keyNodeOrEntry;\n if (key === undefined || key === null) return [undefined, undefined];\n const finalValue = value ?? entryValue;\n return [this.createNode(key, finalValue, 'BLACK', count), finalValue];\n }\n\n return [this.createNode(keyNodeOrEntry, value, 'BLACK', count), value];\n }\n\n /**\n * (Protected) Swap keys/values/counters between the source and destination nodes.\n * @remarks Time O(1), Space O(1)\n * @param srcNode - Source node (or key) whose properties will be moved.\n * @param destNode - Destination node (or key) to receive properties.\n * @returns Destination node after swap, or undefined.\n */\n protected override _swapProperties(\n srcNode: BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>,\n destNode: BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>\n ): TreeCounterNode<K, V> | undefined {\n srcNode = this.ensureNode(srcNode);\n destNode = this.ensureNode(destNode);\n if (srcNode && destNode) {\n const { key, value, count, color } = destNode;\n const tempNode = this.createNode(key, value, color, count);\n if (tempNode) {\n tempNode.color = color;\n\n destNode.key = srcNode.key;\n if (!this._isMapMode) destNode.value = srcNode.value;\n destNode.count = srcNode.count;\n destNode.color = srcNode.color;\n\n srcNode.key = tempNode.key;\n if (!this._isMapMode) srcNode.value = tempNode.value;\n srcNode.count = tempNode.count;\n srcNode.color = tempNode.color;\n }\n\n return destNode;\n }\n return undefined;\n }\n\n /**\n * (Protected) Replace one node by another and adjust counters accordingly.\n * @remarks Time O(1), Space O(1)\n * @param oldNode - Node being replaced.\n * @param newNode - Replacement node.\n * @returns The new node after replacement.\n */\n\n protected override _replaceNode(\n oldNode: TreeCounterNode<K, V>,\n newNode: TreeCounterNode<K, V>\n ): TreeCounterNode<K, V> {\n newNode.count = oldNode.count + newNode.count;\n return super._replaceNode(oldNode, newNode);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type {\n AVLTreeCounterOptions,\n BinaryTreeDeleteResult,\n BSTNOptKeyOrNode,\n EntryCallback,\n FamilyPosition,\n IterationType,\n RBTNColor\n} from '../../types';\nimport { IBinaryTree } from '../../interfaces';\nimport { AVLTree } from './avl-tree';\n\n/**\n * AVL node with an extra 'count' field; keeps parent/child links.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n */\nexport class AVLTreeCounterNode<K = any, V = any> {\n key: K;\n value?: V;\n parent?: AVLTreeCounterNode<K, V> = undefined;\n\n /**\n * Create an AVL counter node.\n * @remarks Time O(1), Space O(1)\n * @param key - Key of the node.\n * @param [value] - Associated value (ignored in map mode).\n * @param [count] - Initial count for this node (default 1).\n * @returns New AVLTreeCounterNode instance.\n */\n constructor(key: K, value?: V, count = 1) {\n this.key = key;\n this.value = value;\n this.count = count;\n }\n\n _left?: AVLTreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the left child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Left child node, or null/undefined.\n */\n get left(): AVLTreeCounterNode<K, V> | null | undefined {\n return this._left;\n }\n\n /**\n * Set the left child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New left child node, or null/undefined.\n * @returns void\n */\n set left(v: AVLTreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._left = v;\n }\n\n _right?: AVLTreeCounterNode<K, V> | null | undefined = undefined;\n\n /**\n * Get the right child pointer.\n * @remarks Time O(1), Space O(1)\n * @returns Right child node, or null/undefined.\n */\n get right(): AVLTreeCounterNode<K, V> | null | undefined {\n return this._right;\n }\n\n /**\n * Set the right child and update its parent pointer.\n * @remarks Time O(1), Space O(1)\n * @param v - New right child node, or null/undefined.\n * @returns void\n */\n set right(v: AVLTreeCounterNode<K, V> | null | undefined) {\n if (v) {\n v.parent = this;\n }\n this._right = v;\n }\n\n _height: number = 0;\n\n /**\n * Gets the height of the node (used in self-balancing trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The height.\n */\n get height(): number {\n return this._height;\n }\n\n /**\n * Sets the height of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new height.\n */\n set height(value: number) {\n this._height = value;\n }\n\n _color: RBTNColor = 'BLACK';\n\n /**\n * Gets the color of the node (used in Red-Black trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The node's color.\n */\n get color(): RBTNColor {\n return this._color;\n }\n\n /**\n * Sets the color of the node.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new color.\n */\n set color(value: RBTNColor) {\n this._color = value;\n }\n\n _count: number = 1;\n\n /**\n * Gets the count of nodes in the subtree rooted at this node (used in order-statistic trees).\n * @remarks Time O(1), Space O(1)\n *\n * @returns The subtree node count.\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * Sets the count of nodes in the subtree.\n * @remarks Time O(1), Space O(1)\n *\n * @param value - The new count.\n */\n set count(value: number) {\n this._count = value;\n }\n\n /**\n * Gets the position of the node relative to its parent.\n * @remarks Time O(1), Space O(1)\n *\n * @returns The family position (e.g., 'ROOT', 'LEFT', 'RIGHT').\n */\n get familyPosition(): FamilyPosition {\n if (!this.parent) {\n return this.left || this.right ? 'ROOT' : 'ISOLATED';\n }\n\n if (this.parent.left === this) {\n return this.left || this.right ? 'ROOT_LEFT' : 'LEFT';\n } else if (this.parent.right === this) {\n return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';\n }\n\n return 'MAL_NODE';\n }\n}\n\n/**\n * AVL tree that tracks an aggregate 'count' across nodes; supports balanced insert/delete and map-like mode.\n * @remarks Time O(1), Space O(1)\n * @template K\n * @template V\n * @template R\n */\nexport class AVLTreeCounter<K = any, V = any, R = any> extends AVLTree<K, V, R> implements IBinaryTree<K, V, R> {\n /**\n * Create a AVLTreeCounter instance\n * @remarks Time O(n), Space O(n)\n * @param keysNodesEntriesOrRaws\n * @param options\n * @returns New AVLTreeCounterNode instance.\n */\n constructor(\n keysNodesEntriesOrRaws: Iterable<\n K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R\n > = [],\n options?: AVLTreeCounterOptions<K, V, R>\n ) {\n super([], options);\n if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);\n }\n\n protected _count = 0;\n\n get count(): number {\n return this._count;\n }\n\n /**\n * Compute the total count by traversing the tree (sums node.count).\n * @remarks Time O(N), Space O(H)\n * @returns Total count recomputed from nodes.\n */\n getComputedCount(): number {\n let sum = 0;\n this.dfs(node => (sum += node.count));\n return sum;\n }\n\n override createNode(key: K, value?: V, count?: number): AVLTreeCounterNode<K, V> {\n return new AVLTreeCounterNode(key, this._isMapMode ? undefined : value, count) as AVLTreeCounterNode<K, V>;\n }\n\n /**\n * Type guard: check whether the input is an AVLTreeCounterNode.\n * @remarks Time O(1), Space O(1)\n * @returns True if the value is an AVLTreeCounterNode.\n */\n override isNode(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined\n ): keyNodeOrEntry is AVLTreeCounterNode<K, V> {\n return keyNodeOrEntry instanceof AVLTreeCounterNode;\n }\n\n /**\n * Insert or increment a node and update aggregate count.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.\n * @param [value] - Value when a bare key is provided (ignored in map mode).\n * @param [count] - How much to increase the node's count (default 1).\n * @returns True if inserted/updated; false if ignored.\n */\n override add(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): boolean {\n const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value, count);\n if (newNode === undefined) return false;\n\n const orgNodeCount = newNode?.count || 0;\n const inserted = super.add(newNode, newValue);\n if (inserted) {\n this._count += orgNodeCount;\n }\n return true;\n }\n\n /**\n * Delete a node (or decrement its count) and rebalance if needed.\n * @remarks Time O(log N), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node.\n * @param [ignoreCount] - If true, remove the node regardless of its count.\n * @returns Array of deletion results including deleted node and a rebalance hint when present.\n */\n override delete(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n ignoreCount = false\n ): BinaryTreeDeleteResult<AVLTreeCounterNode<K, V>>[] {\n const deletedResult: BinaryTreeDeleteResult<AVLTreeCounterNode<K, V>>[] = [];\n if (!this.root) return deletedResult;\n\n const curr: AVLTreeCounterNode<K, V> | undefined = this.getNode(keyNodeOrEntry) ?? undefined;\n if (!curr) return deletedResult;\n\n const parent: AVLTreeCounterNode<K, V> | undefined = curr?.parent ? curr.parent : undefined;\n let needBalanced: AVLTreeCounterNode<K, V> | undefined = undefined,\n orgCurrent: AVLTreeCounterNode<K, V> | undefined = curr;\n\n if (curr.count > 1 && !ignoreCount) {\n curr.count--;\n this._count--;\n } else {\n if (!curr.left) {\n if (!parent) {\n if (curr.right !== undefined && curr.right !== null) this._setRoot(curr.right);\n } else {\n const { familyPosition: fp } = curr;\n if (fp === 'LEFT' || fp === 'ROOT_LEFT') {\n parent.left = curr.right;\n } else if (fp === 'RIGHT' || fp === 'ROOT_RIGHT') {\n parent.right = curr.right;\n }\n needBalanced = parent;\n }\n } else {\n const leftSubTreeRightMost = curr.left ? this.getRightMost(node => node, curr.left) : undefined;\n if (leftSubTreeRightMost) {\n const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;\n orgCurrent = this._swapProperties(curr, leftSubTreeRightMost);\n if (parentOfLeftSubTreeMax) {\n if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost) {\n parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;\n } else {\n parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;\n }\n needBalanced = parentOfLeftSubTreeMax;\n }\n }\n }\n this._size = this._size - 1;\n\n if (orgCurrent) this._count -= orgCurrent.count;\n }\n\n deletedResult.push({ deleted: orgCurrent, needBalanced });\n\n if (needBalanced) {\n this._balancePath(needBalanced);\n }\n\n return deletedResult;\n }\n\n /**\n * Remove all nodes and reset aggregate counters.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n override clear() {\n super.clear();\n this._count = 0;\n }\n\n /**\n * Rebuild the tree into a perfectly balanced form using in-order nodes.\n * @remarks Time O(N), Space O(N)\n * @param [iterationType] - Traversal style to use when constructing the balanced tree.\n * @returns True if rebalancing succeeded (tree not empty).\n */\n override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {\n const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);\n const n = nodes.length;\n if (n === 0) return false;\n\n let total = 0;\n for (const nd of nodes) total += nd ? nd.count : 0;\n\n this._clearNodes();\n\n const build = (l: number, r: number, parent?: any): any => {\n if (l > r) return undefined;\n const m = l + ((r - l) >> 1);\n const root = nodes[m];\n root.left = build(l, m - 1, root);\n root.right = build(m + 1, r, root);\n root.parent = parent;\n const lh = root.left ? root.left.height : -1;\n const rh = root.right ? root.right.height : -1;\n root.height = Math.max(lh, rh) + 1;\n return root;\n };\n\n const newRoot = build(0, n - 1, undefined);\n this._setRoot(newRoot);\n this._size = n;\n this._count = total;\n return true;\n }\n\n /**\n * Deep copy this tree, preserving map mode and aggregate counts.\n * @remarks Time O(N), Space O(N)\n * @returns A deep copy of this tree.\n */\n override clone(): this {\n const out = this._createInstance();\n\n if (this._isMapMode) {\n this.bfs(node => out.add(node.key, undefined, node.count));\n } else {\n this.bfs(node => out.add(node.key, node.value, node.count));\n }\n\n if (this._isMapMode) out._store = this._store;\n\n return out as this;\n }\n\n /**\n * Create a new AVLTreeCounter by mapping each [key, value] entry.\n * @remarks Time O(N log N), Space O(N)\n * @template MK\n * @template MV\n * @template MR\n * @param callback - Function mapping (key, value, index, tree) → [newKey, newValue].\n * @param [options] - Options for the output tree.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new AVLTreeCounter with mapped entries.\n */\n override map<MK = K, MV = V, MR = any>(\n callback: EntryCallback<K, V | undefined, [MK, MV]>,\n options?: Partial<AVLTreeCounterOptions<MK, MV, MR>>,\n thisArg?: unknown\n ): AVLTreeCounter<MK, MV, MR> {\n const out = this._createLike<MK, MV, MR>([], options);\n\n let index = 0;\n for (const [key, value] of this) {\n out.add(callback.call(thisArg, value, key, index++, this));\n }\n return out;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @template TK\n * @template TV\n * @template TR\n * @param [options] - Optional constructor options for the like-kind instance.\n * @returns An empty like-kind instance.\n */\n protected override _createInstance<TK = K, TV = V, TR = R>(\n options?: Partial<AVLTreeCounterOptions<TK, TV, TR>>\n ): this {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<\n TK | AVLTreeCounterNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n >,\n opts?: AVLTreeCounterOptions<TK, TV, TR>\n ) => AVLTreeCounter<TK, TV, TR>;\n return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;\n }\n\n /**\n * (Protected) Create a like-kind instance and seed it from an iterable.\n * @remarks Time O(N log N), Space O(N)\n * @template TK\n * @template TV\n * @template TR\n * @param iter - Iterable used to seed the new tree.\n * @param [options] - Options merged with the current snapshot.\n * @returns A like-kind AVLTreeCounter built from the iterable.\n */\n protected override _createLike<TK = K, TV = V, TR = R>(\n iter: Iterable<\n TK | AVLTreeCounterNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n > = [],\n options?: Partial<AVLTreeCounterOptions<TK, TV, TR>>\n ): AVLTreeCounter<TK, TV, TR> {\n const Ctor = this.constructor as unknown as new (\n iter?: Iterable<\n TK | AVLTreeCounterNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR\n >,\n opts?: AVLTreeCounterOptions<TK, TV, TR>\n ) => AVLTreeCounter<TK, TV, TR>;\n return new Ctor(iter, { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) });\n }\n\n /**\n * (Protected) Normalize input into a node plus its effective value and count.\n * @remarks Time O(1), Space O(1)\n * @param keyNodeOrEntry - Key, node, or [key, value] entry.\n * @param [value] - Value used when a bare key is provided.\n * @param [count] - Count increment to apply (default 1).\n * @returns Tuple [node, value] where node may be undefined.\n */\n protected override _keyValueNodeOrEntryToNodeAndValue(\n keyNodeOrEntry: K | AVLTreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,\n value?: V,\n count = 1\n ): [AVLTreeCounterNode<K, V> | undefined, V | undefined] {\n if (keyNodeOrEntry === undefined || keyNodeOrEntry === null) return [undefined, undefined];\n if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];\n\n if (this.isEntry(keyNodeOrEntry)) {\n const [key, entryValue] = keyNodeOrEntry;\n if (key === undefined || key === null) return [undefined, undefined];\n const finalValue = value ?? entryValue;\n return [this.createNode(key, finalValue, count), finalValue];\n }\n\n return [this.createNode(keyNodeOrEntry, value, count), value];\n }\n\n /**\n * (Protected) Swap keys/values/counters between the source and destination nodes.\n * @remarks Time O(1), Space O(1)\n * @param srcNode - Source node (or key) whose properties will be moved.\n * @param destNode - Destination node (or key) to receive properties.\n * @returns Destination node after swap, or undefined.\n */\n protected override _swapProperties(\n srcNode: BSTNOptKeyOrNode<K, AVLTreeCounterNode<K, V>>,\n destNode: BSTNOptKeyOrNode<K, AVLTreeCounterNode<K, V>>\n ): AVLTreeCounterNode<K, V> | undefined {\n srcNode = this.ensureNode(srcNode);\n destNode = this.ensureNode(destNode);\n if (srcNode && destNode) {\n const { key, value, count, height } = destNode;\n const tempNode = this.createNode(key, value, count);\n if (tempNode) {\n tempNode.height = height;\n\n destNode.key = srcNode.key;\n if (!this._isMapMode) destNode.value = srcNode.value;\n destNode.count = srcNode.count;\n destNode.height = srcNode.height;\n\n srcNode.key = tempNode.key;\n if (!this._isMapMode) srcNode.value = tempNode.value;\n srcNode.count = tempNode.count;\n srcNode.height = tempNode.height;\n }\n\n return destNode;\n }\n return undefined;\n }\n\n /**\n * (Protected) Replace one node by another and adjust counters accordingly.\n * @remarks Time O(1), Space O(1)\n * @param oldNode - Node being replaced.\n * @param newNode - Replacement node.\n * @returns The new node after replacement.\n */\n protected override _replaceNode(\n oldNode: AVLTreeCounterNode<K, V>,\n newNode: AVLTreeCounterNode<K, V>\n ): AVLTreeCounterNode<K, V> {\n newNode.count = oldNode.count + newNode.count;\n return super._replaceNode(oldNode, newNode);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\n\nimport type { PriorityQueueOptions } from '../../types';\nimport { Heap } from '../heap';\n\n/**\n * @example\n */\nexport class PriorityQueue<E = any, R = any> extends Heap<E, R> {\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Min-oriented priority queue (min-heap) built on {@link PriorityQueue}.\n * The queue removes the smallest element first under the provided comparator.\n * Provide a custom comparator if you store non-primitive objects.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MinPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a min-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, options);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Kirk Qi\n * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>\n * @license MIT License\n */\nimport type { PriorityQueueOptions } from '../../types';\nimport { PriorityQueue } from './priority-queue';\n\n/**\n * Max-oriented priority queue (max-heap) built on {@link PriorityQueue}.\n * The default comparator orders primitive values in descending order. If you store objects,\n * you must provide a custom comparator via {@link PriorityQueueOptions}.\n * @template E Element type stored in the queue.\n * @template R Extra record/metadata associated with each element.\n * @example\n */\nexport class MaxPriorityQueue<E = any, R = any> extends PriorityQueue<E, R> {\n /**\n * Creates a max-priority queue.\n * @param elements Optional initial elements to insert.\n * @param options Optional configuration (e.g., `comparator`, `toElementFn`).\n * @throws {TypeError} Thrown when using the default comparator with object elements (provide a custom comparator).\n * @remarks Complexity — Time: O(n log n) when inserting n elements incrementally; Space: O(n).\n */\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: PriorityQueueOptions<E, R>) {\n super(elements, {\n comparator: (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError(\n `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`\n );\n }\n if (a < b) return 1;\n if (a > b) return -1;\n return 0;\n },\n ...options\n });\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { MatrixOptions } from '../../types';\n\n/**\n *\n */\nexport class Matrix {\n /**\n * The constructor function initializes a matrix object with the provided data and options, or with\n * default values if no options are provided.\n * @param {number[][]} data - A 2D array of numbers representing the data for the matrix.\n * @param [options] - The `options` parameter is an optional object that can contain the following\n * properties:\n */\n constructor(data: number[][], options?: MatrixOptions) {\n if (options) {\n const { rows, cols, addFn, subtractFn, multiplyFn } = options;\n if (typeof rows === 'number' && rows > 0) this._rows = rows;\n else this._rows = data.length;\n if (typeof cols === 'number' && cols > 0) this._cols = cols;\n else this._cols = data[0]?.length || 0;\n if (addFn) this._addFn = addFn;\n if (subtractFn) this._subtractFn = subtractFn;\n if (multiplyFn) this._multiplyFn = multiplyFn;\n } else {\n this._rows = data.length;\n this._cols = data[0]?.length ?? 0;\n }\n\n if (data.length > 0) {\n this._data = data;\n } else {\n this._data = [];\n for (let i = 0; i < this.rows; i++) {\n this._data[i] = new Array(this.cols).fill(0);\n }\n }\n }\n\n protected _rows: number = 0;\n\n /**\n * The function returns the number of rows.\n * @returns The number of rows.\n */\n get rows(): number {\n return this._rows;\n }\n\n protected _cols: number = 0;\n\n /**\n * The function returns the value of the protected variable _cols.\n * @returns The number of columns.\n */\n get cols(): number {\n return this._cols;\n }\n\n protected _data: number[][];\n\n /**\n * The function returns a two-dimensional array of numbers.\n * @returns The data property, which is a two-dimensional array of numbers.\n */\n get data(): number[][] {\n return this._data;\n }\n\n /**\n * The above function returns the value of the _addFn property.\n * @returns The value of the property `_addFn` is being returned.\n */\n get addFn() {\n return this._addFn;\n }\n\n /**\n * The function returns the value of the _subtractFn property.\n * @returns The `_subtractFn` property is being returned.\n */\n get subtractFn() {\n return this._subtractFn;\n }\n\n /**\n * The function returns the value of the _multiplyFn property.\n * @returns The `_multiplyFn` property is being returned.\n */\n get multiplyFn() {\n return this._multiplyFn;\n }\n\n /**\n * The `get` function returns the value at the specified row and column index if it is a valid index.\n * @param {number} row - The `row` parameter represents the row index of the element you want to\n * retrieve from the data array.\n * @param {number} col - The parameter \"col\" represents the column number of the element you want to\n * retrieve from the data array.\n * @returns The `get` function returns a number if the provided row and column indices are valid.\n * Otherwise, it returns `undefined`.\n */\n get(row: number, col: number): number | undefined {\n if (this.isValidIndex(row, col)) {\n return this.data[row][col];\n }\n }\n\n /**\n * The set function updates the value at a specified row and column in a two-dimensional array.\n * @param {number} row - The \"row\" parameter represents the row index of the element in a\n * two-dimensional array or matrix. It specifies the row where the value will be set.\n * @param {number} col - The \"col\" parameter represents the column index of the element in a\n * two-dimensional array.\n * @param {number} value - The value parameter represents the number that you want to set at the\n * specified row and column in the data array.\n * @returns a boolean value. It returns true if the index (row, col) is valid and the value is\n * successfully set in the data array. It returns false if the index is invalid and the value is not\n * set.\n */\n set(row: number, col: number, value: number): boolean {\n if (this.isValidIndex(row, col)) {\n this.data[row][col] = value;\n return true;\n }\n return false;\n }\n\n /**\n * The function checks if the dimensions of the given matrix match the dimensions of the current\n * matrix.\n * @param {Matrix} matrix - The parameter `matrix` is of type `Matrix`.\n * @returns a boolean value.\n */\n isMatchForCalculate(matrix: Matrix): boolean {\n return this.rows === matrix.rows && this.cols === matrix.cols;\n }\n\n /**\n * The `add` function adds two matrices together, returning a new matrix with the result.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.\n * @returns The `add` method returns a new `Matrix` object that represents the result of adding the\n * current matrix with the provided `matrix` parameter.\n */\n add(matrix: Matrix): Matrix | undefined {\n if (!this.isMatchForCalculate(matrix)) {\n throw new Error('Matrix dimensions must match for addition.');\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < this.cols; j++) {\n const a = this.get(i, j),\n b = matrix.get(i, j);\n if (a !== undefined && b !== undefined) {\n const added = this._addFn(a, b);\n if (added) {\n resultData[i][j] = added;\n }\n }\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The `subtract` function performs element-wise subtraction between two matrices and returns a new\n * matrix with the result.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class. It\n * represents the matrix that you want to subtract from the current matrix.\n * @returns a new Matrix object with the result of the subtraction operation.\n */\n subtract(matrix: Matrix): Matrix | undefined {\n if (!this.isMatchForCalculate(matrix)) {\n throw new Error('Matrix dimensions must match for subtraction.');\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < this.cols; j++) {\n const a = this.get(i, j),\n b = matrix.get(i, j);\n if (a !== undefined && b !== undefined) {\n const subtracted = this._subtractFn(a, b);\n if (subtracted) {\n resultData[i][j] = subtracted;\n }\n }\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The `multiply` function performs matrix multiplication between two matrices and returns the result\n * as a new matrix.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.\n * @returns a new Matrix object.\n */\n multiply(matrix: Matrix): Matrix | undefined {\n if (this.cols !== matrix.rows) {\n throw new Error('Matrix dimensions must be compatible for multiplication (A.cols = B.rows).');\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < matrix.cols; j++) {\n let sum: number | undefined;\n for (let k = 0; k < this.cols; k++) {\n const a = this.get(i, k),\n b = matrix.get(k, j);\n if (a !== undefined && b !== undefined) {\n const multiplied = this.multiplyFn(a, b);\n if (multiplied !== undefined) {\n sum = this.addFn(sum, multiplied);\n }\n }\n }\n if (sum !== undefined) resultData[i][j] = sum;\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: matrix.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The transpose function takes a matrix and returns a new matrix that is the transpose of the\n * original matrix.\n * @returns The transpose() function returns a new Matrix object with the transposed data.\n */\n transpose(): Matrix {\n if (this.data.some(row => row.length !== this.rows)) {\n throw new Error('Matrix must be rectangular for transposition.');\n }\n\n const resultData: number[][] = [];\n\n for (let j = 0; j < this.cols; j++) {\n resultData[j] = [];\n for (let i = 0; i < this.rows; i++) {\n const trans = this.get(i, j);\n if (trans !== undefined) resultData[j][i] = trans;\n }\n }\n\n return new Matrix(resultData, {\n rows: this.cols,\n cols: this.rows,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The `inverse` function calculates the inverse of a square matrix using Gaussian elimination.\n * @returns a Matrix object, which represents the inverse of the original matrix.\n */\n inverse(): Matrix | undefined {\n // Check if the matrix is square\n if (this.rows !== this.cols) {\n throw new Error('Matrix must be square for inversion.');\n }\n\n // Create an augmented matrix [this | I]\n const augmentedMatrixData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n augmentedMatrixData[i] = this.data[i].slice(); // Copy the original matrix\n for (let j = 0; j < this.cols; j++) {\n augmentedMatrixData[i][this.cols + j] = i === j ? 1 : 0; // Append the identity matrix\n }\n }\n\n const augmentedMatrix = new Matrix(augmentedMatrixData, {\n rows: this.rows,\n cols: this.cols * 2,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n\n // Apply Gaussian elimination to transform the left half into the identity matrix\n for (let i = 0; i < this.rows; i++) {\n // Find pivot\n let pivotRow = i;\n while (pivotRow < this.rows && augmentedMatrix.get(pivotRow, i) === 0) {\n pivotRow++;\n }\n\n if (pivotRow === this.rows) {\n // Matrix is singular, and its inverse does not exist\n throw new Error('Matrix is singular, and its inverse does not exist.');\n }\n\n // Swap rows to make the pivot the current row\n augmentedMatrix._swapRows(i, pivotRow);\n\n // Scale the pivot row to make the pivot element 1\n const pivotElement = augmentedMatrix.get(i, i) ?? 1;\n\n if (pivotElement === 0) {\n // Handle division by zero\n throw new Error('Matrix is singular, and its inverse does not exist (division by zero).');\n }\n\n augmentedMatrix._scaleRow(i, 1 / pivotElement);\n\n // Eliminate other rows to make elements in the current column zero\n for (let j = 0; j < this.rows; j++) {\n if (j !== i) {\n let factor = augmentedMatrix.get(j, i);\n if (factor === undefined) factor = 0;\n\n augmentedMatrix._addScaledRow(j, i, -factor);\n }\n }\n }\n\n // Extract the right half of the augmented matrix as the inverse\n const inverseData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n inverseData[i] = augmentedMatrix.data[i].slice(this.cols);\n }\n\n return new Matrix(inverseData, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The dot function calculates the dot product of two matrices and returns a new matrix.\n * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.\n * @returns a new Matrix object.\n */\n dot(matrix: Matrix): Matrix | undefined {\n if (this.cols !== matrix.rows) {\n throw new Error(\n 'Number of columns in the first matrix must be equal to the number of rows in the second matrix for dot product.'\n );\n }\n\n const resultData: number[][] = [];\n for (let i = 0; i < this.rows; i++) {\n resultData[i] = [];\n for (let j = 0; j < matrix.cols; j++) {\n let sum: number | undefined;\n for (let k = 0; k < this.cols; k++) {\n const a = this.get(i, k),\n b = matrix.get(k, j);\n if (a !== undefined && b !== undefined) {\n const multiplied = this.multiplyFn(a, b);\n if (multiplied !== undefined) {\n sum = this.addFn(sum, multiplied);\n }\n }\n }\n if (sum !== undefined) resultData[i][j] = sum;\n }\n }\n\n return new Matrix(resultData, {\n rows: this.rows,\n cols: matrix.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n /**\n * The function checks if a given row and column index is valid within a specified range.\n * @param {number} row - The `row` parameter represents the row index of a two-dimensional array or\n * matrix. It is a number that indicates the specific row in the matrix.\n * @param {number} col - The \"col\" parameter represents the column index in a two-dimensional array\n * or grid. It is used to check if the given column index is valid within the bounds of the grid.\n * @returns A boolean value is being returned.\n */\n isValidIndex(row: number, col: number): boolean {\n return row >= 0 && row < this.rows && col >= 0 && col < this.cols;\n }\n\n /**\n * The `clone` function returns a new instance of the Matrix class with the same data and properties\n * as the original instance.\n * @returns The `clone()` method is returning a new instance of the `Matrix` class with the same data\n * and properties as the current instance.\n */\n clone(): Matrix {\n return new Matrix(this.data, {\n rows: this.rows,\n cols: this.cols,\n addFn: this.addFn,\n subtractFn: this.subtractFn,\n multiplyFn: this.multiplyFn\n });\n }\n\n protected _addFn(a: number | undefined, b: number): number | undefined {\n if (a === undefined) return b;\n return a + b;\n }\n\n protected _subtractFn(a: number, b: number) {\n return a - b;\n }\n\n protected _multiplyFn(a: number, b: number) {\n return a * b;\n }\n\n /**\n * The function `_swapRows` swaps the positions of two rows in an array.\n * @param {number} row1 - The `row1` parameter is the index of the first row that you want to swap.\n * @param {number} row2 - The `row2` parameter is the index of the second row that you want to swap\n * with the first row.\n */\n protected _swapRows(row1: number, row2: number): void {\n const temp = this.data[row1];\n this.data[row1] = this.data[row2];\n this.data[row2] = temp;\n }\n\n /**\n * The function scales a specific row in a matrix by a given scalar value.\n * @param {number} row - The `row` parameter represents the index of the row in the matrix that you\n * want to scale. It is a number that indicates the position of the row within the matrix.\n * @param {number} scalar - The scalar parameter is a number that is used to multiply each element in\n * a specific row of a matrix.\n */\n protected _scaleRow(row: number, scalar: number): void {\n for (let j = 0; j < this.cols; j++) {\n let multiplied = this.multiplyFn(this.data[row][j], scalar);\n if (multiplied === undefined) multiplied = 0;\n this.data[row][j] = multiplied;\n }\n }\n\n /**\n * The function `_addScaledRow` multiplies a row in a matrix by a scalar value and adds it to another\n * row.\n * @param {number} targetRow - The targetRow parameter represents the index of the row in which the\n * scaled values will be added.\n * @param {number} sourceRow - The sourceRow parameter represents the index of the row from which the\n * values will be scaled and added to the targetRow.\n * @param {number} scalar - The scalar parameter is a number that is used to scale the values in the\n * source row before adding them to the target row.\n */\n protected _addScaledRow(targetRow: number, sourceRow: number, scalar: number): void {\n for (let j = 0; j < this.cols; j++) {\n let multiplied = this.multiplyFn(this.data[sourceRow][j], scalar);\n if (multiplied === undefined) multiplied = 0;\n const scaledValue = multiplied;\n let added = this.addFn(this.data[targetRow][j], scaledValue);\n if (added === undefined) added = 0;\n this.data[targetRow][j] = added;\n }\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Direction, NavigatorParams, Turning } from '../../types';\n\nexport class Character {\n direction: Direction;\n turn: () => Character;\n\n /**\n * The constructor function takes in a direction and turning object and sets the direction and turn properties of the\n * Character class.\n * @param {Direction} direction - The direction parameter is used to specify the current direction of the character. It\n * can be any value that represents a direction, such as \"north\", \"south\", \"east\", or \"west\".\n * @param {Turning} turning - The `turning` parameter is an object that maps each direction to the corresponding\n * turning direction. It is used to determine the new direction when the character turns.\n */\n constructor(direction: Direction, turning: Turning) {\n this.direction = direction;\n this.turn = () => new Character(turning[direction], turning);\n }\n}\n\n/**\n *\n */\nexport class Navigator<T = number> {\n onMove: (cur: [number, number]) => void;\n protected readonly _matrix: T[][];\n protected readonly _cur: [number, number];\n protected _character: Character;\n protected readonly _VISITED: T;\n\n /**\n * The constructor initializes the Navigator object with the given parameters and sets the current position as visited\n * in the matrix.\n * @param - - `matrix`: a 2D array representing the grid or map\n */\n constructor({ matrix, turning, onMove, init: { cur, charDir, VISITED } }: NavigatorParams<T>) {\n this._matrix = matrix;\n this._cur = cur;\n this._character = new Character(charDir, turning);\n this.onMove = onMove;\n if (this.onMove) this.onMove(this._cur);\n this._VISITED = VISITED;\n this._matrix[this._cur[0]][this._cur[1]] = this._VISITED;\n }\n\n /**\n * The \"start\" function moves the character in its current direction until it encounters an obstacle, then it turns the\n * character and repeats the process.\n */\n start() {\n while (this.check(this._character.direction) || this.check(this._character.turn().direction)) {\n const { direction } = this._character;\n if (this.check(direction)) {\n this.move(direction);\n } else if (this.check(this._character.turn().direction)) {\n this._character = this._character.turn();\n }\n }\n }\n\n /**\n * The function checks if there is a valid move in the specified direction in a matrix.\n * @param {Direction} direction - The direction parameter is a string that represents the direction in which to check.\n * It can be one of the following values: 'up', 'right', 'down', or 'left'.\n * @returns a boolean value.\n */\n check(direction: Direction) {\n let forward: T | undefined, row: T[] | undefined;\n const matrix = this._matrix;\n const [i, j] = this._cur;\n switch (direction) {\n case 'up':\n row = matrix[i - 1];\n if (!row) return false;\n forward = row[j];\n break;\n case 'right':\n forward = matrix[i][j + 1];\n break;\n case 'down':\n row = matrix[i + 1];\n if (!row) return false;\n forward = row[j];\n break;\n case 'left':\n forward = matrix[i][j - 1];\n break;\n }\n return forward !== undefined && forward !== this._VISITED;\n }\n\n /**\n * The `move` function updates the current position based on the given direction and updates the matrix accordingly.\n * @param {Direction} direction - The `direction` parameter is a string that represents the direction in which to move.\n * It can have one of the following values: 'up', 'right', 'down', or 'left'.\n */\n move(direction: Direction) {\n switch (direction) {\n case 'up':\n this._cur[0]--;\n break;\n case 'right':\n this._cur[1]++;\n break;\n case 'down':\n this._cur[0]++;\n break;\n case 'left':\n this._cur[1]--;\n break;\n }\n\n const [i, j] = this._cur;\n this._matrix[i][j] = this._VISITED;\n if (this.onMove) this.onMove(this._cur);\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, TrieOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Node used by Trie to store one character and its children.\n * @remarks Time O(1), Space O(1)\n */\nexport class TrieNode {\n /**\n * Create a Trie node with a character key.\n * @remarks Time O(1), Space O(1)\n * @returns New TrieNode instance.\n */\n\n constructor(key: string) {\n this._key = key;\n this._isEnd = false;\n this._children = new Map<string, TrieNode>();\n }\n\n protected _key: string;\n\n /**\n * Get the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Character key string.\n */\n\n get key(): string {\n return this._key;\n }\n\n /**\n * Set the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New character key.\n * @returns void\n */\n\n set key(value: string) {\n this._key = value;\n }\n\n protected _children: Map<string, TrieNode>;\n\n /**\n * Get the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Map from character to child node.\n */\n\n get children(): Map<string, TrieNode> {\n return this._children;\n }\n\n /**\n * Replace the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New map of character → node.\n * @returns void\n */\n\n set children(value: Map<string, TrieNode>) {\n this._children = value;\n }\n\n protected _isEnd: boolean;\n\n /**\n * Check whether this node marks the end of a word.\n * @remarks Time O(1), Space O(1)\n * @returns True if this node ends a word.\n */\n\n get isEnd(): boolean {\n return this._isEnd;\n }\n\n /**\n * Mark this node as the end of a word or not.\n * @remarks Time O(1), Space O(1)\n * @param value - Whether this node ends a word.\n * @returns void\n */\n\n set isEnd(value: boolean) {\n this._isEnd = value;\n }\n}\n\n/**\n * Prefix tree (Trie) for fast prefix queries and word storage.\n * @remarks Time O(1), Space O(1)\n * @template R\n * 1. Node Structure: Each node in a Trie represents a string (or a part of a string). The root node typically represents an empty string.\n * 2. Child Node Relationship: Each node's children represent the strings that can be formed by adding one character to the string at the current node. For example, if a node represents the string 'ca', one of its children might represent 'cat'.\n * 3. Fast Retrieval: Trie allows retrieval in O(m) time complexity, where m is the length of the string to be searched.\n * 4. Space Efficiency: Trie can store a large number of strings very space-efficiently, especially when these strings share common prefixes.\n * 5. Autocomplete and Prediction: Trie can be used for implementing autocomplete and word prediction features, as it can quickly find all strings with a common prefix.\n * 6. Sorting: Trie can be used to sort a set of strings in alphabetical order.\n * 7. String Retrieval: For example, searching for a specific string in a large set of strings.\n * 8. Autocomplete: Providing recommended words or phrases as a user types.\n * 9. Spell Check: Checking the spelling of words.\n * 10. IP Routing: Used in certain types of IP routing algorithms.\n * 11. Text Word Frequency Count: Counting and storing the frequency of words in a large amount of text data.\n * @example\n * // basic Trie creation and add words\n * // Create a simple Trie with initial words\n * const trie = new Trie(['apple', 'app', 'apply']);\n *\n * // Verify size\n * console.log(trie.size); // 3;\n *\n * // Check if words exist\n * console.log(trie.has('apple')); // true;\n * console.log(trie.has('app')); // true;\n *\n * // Add a new word\n * trie.add('application');\n * console.log(trie.size); // 4;\n * @example\n * // Trie getWords and prefix search\n * const trie = new Trie(['apple', 'app', 'apply', 'application', 'apricot']);\n *\n * // Get all words with prefix 'app'\n * const appWords = trie.getWords('app');\n * console.log(appWords); // contains 'app';\n * console.log(appWords); // contains 'apple';\n * console.log(appWords); // contains 'apply';\n * console.log(appWords); // contains 'application';\n * expect(appWords).not.toContain('apricot');\n * @example\n * // Trie isPrefix and isAbsolutePrefix checks\n * const trie = new Trie(['tree', 'trial', 'trick', 'trip', 'trie']);\n *\n * // Check if string is a prefix of any word\n * console.log(trie.hasPrefix('tri')); // true;\n * console.log(trie.hasPrefix('tr')); // true;\n * console.log(trie.hasPrefix('xyz')); // false;\n *\n * // Check if string is an absolute prefix (not a complete word)\n * console.log(trie.hasPurePrefix('tri')); // true;\n * console.log(trie.hasPurePrefix('tree')); // false; // 'tree' is a complete word\n *\n * // Verify size\n * console.log(trie.size); // 5;\n * @example\n * // Trie delete and iteration\n * const trie = new Trie(['car', 'card', 'care', 'careful', 'can', 'cat']);\n *\n * // Delete a word\n * trie.delete('card');\n * console.log(trie.has('card')); // false;\n *\n * // Word with same prefix still exists\n * console.log(trie.has('care')); // true;\n *\n * // Size decreased\n * console.log(trie.size); // 5;\n *\n * // Iterate through all words\n * const allWords = [...trie];\n * console.log(allWords.length); // 5;\n * @example\n * // Trie for autocomplete search index\n * // Trie is perfect for autocomplete: O(m + k) where m is prefix length, k is results\n * const searchIndex = new Trie(['typescript', 'javascript', 'python', 'java', 'rust', 'ruby', 'golang', 'kotlin']);\n *\n * // User types 'j' - get all suggestions\n * const jResults = searchIndex.getWords('j');\n * console.log(jResults); // contains 'javascript';\n * console.log(jResults); // contains 'java';\n * console.log(jResults.length); // 2;\n *\n * // User types 'ja' - get more specific suggestions\n * const jaResults = searchIndex.getWords('ja');\n * console.log(jaResults); // contains 'javascript';\n * console.log(jaResults); // contains 'java';\n * console.log(jaResults.length); // 2;\n *\n * // User types 'jav' - even more specific\n * const javResults = searchIndex.getWords('jav');\n * console.log(javResults); // contains 'javascript';\n * console.log(javResults); // contains 'java';\n * console.log(javResults.length); // 2;\n *\n * // Check for common prefix\n *\n * console.log(searchIndex.hasCommonPrefix('ja')); // false; // Not all words start with 'ja'\n *\n * // Total words in index\n * console.log(searchIndex.size); // 8;\n *\n * // Get height (depth of tree)\n * const height = searchIndex.getHeight();\n * console.log(typeof height); // 'number';\n * @example\n * // Dictionary: Case-insensitive word lookup\n * // Create a case-insensitive dictionary\n * const dictionary = new Trie<string>([], { caseSensitive: false });\n *\n * // Add words with mixed casing\n * dictionary.add('Hello');\n * dictionary.add('WORLD');\n * dictionary.add('JavaScript');\n *\n * // Test lookups with different casings\n * console.log(dictionary.has('hello')); // true;\n * console.log(dictionary.has('HELLO')); // true;\n * console.log(dictionary.has('Hello')); // true;\n * console.log(dictionary.has('javascript')); // true;\n * console.log(dictionary.has('JAVASCRIPT')); // true;\n * @example\n * // File System Path Operations\n * const fileSystem = new Trie<string>([\n * '/home/user/documents/file1.txt',\n * '/home/user/documents/file2.txt',\n * '/home/user/pictures/photo.jpg',\n * '/home/user/pictures/vacation/',\n * '/home/user/downloads'\n * ]);\n *\n * // Find common directory prefix\n * console.log(fileSystem.getLongestCommonPrefix()); // '/home/user/';\n *\n * // List all files in a directory\n * const documentsFiles = fileSystem.getWords('/home/user/documents/');\n * console.log(documentsFiles); // ['/home/user/documents/file1.txt', '/home/user/documents/file2.txt'];\n * @example\n * // IP Address Routing Table\n * // Add IP address prefixes and their corresponding routes\n * const routes = {\n * '192.168.1': 'LAN_SUBNET_1',\n * '192.168.2': 'LAN_SUBNET_2',\n * '10.0.0': 'PRIVATE_NETWORK_1',\n * '10.0.1': 'PRIVATE_NETWORK_2'\n * };\n *\n * const ipRoutingTable = new Trie<string>(Object.keys(routes));\n *\n * // Check IP address prefix matching\n * console.log(ipRoutingTable.hasPrefix('192.168.1')); // true;\n * console.log(ipRoutingTable.hasPrefix('192.168.2')); // true;\n *\n * // Validate IP address belongs to subnet\n * const ip = '192.168.1.100';\n * const subnet = ip.split('.').slice(0, 3).join('.');\n * console.log(ipRoutingTable.hasPrefix(subnet)); // true;\n */\nexport class Trie<R = any> extends IterableElementBase<string, R> {\n /**\n * Create a Trie and optionally bulk-insert words.\n * @remarks Time O(totalChars), Space O(totalChars)\n * @param [words] - Iterable of strings (or raw records if toElementFn is provided).\n * @param [options] - Options such as toElementFn and caseSensitive.\n * @returns New Trie instance.\n */\n\n constructor(words: Iterable<string> | Iterable<R> = [], options?: TrieOptions<R>) {\n super(options);\n if (options) {\n const { caseSensitive } = options;\n if (caseSensitive !== undefined) this._caseSensitive = caseSensitive;\n }\n if (words) {\n this.addMany(words);\n }\n }\n\n protected _size: number = 0;\n\n /**\n * Get the number of stored words.\n * @remarks Time O(1), Space O(1)\n * @returns Word count.\n */\n\n get size(): number {\n return this._size;\n }\n\n protected _caseSensitive: boolean = true;\n\n /**\n * Get whether comparisons are case-sensitive.\n * @remarks Time O(1), Space O(1)\n * @returns True if case-sensitive.\n */\n\n get caseSensitive(): boolean {\n return this._caseSensitive;\n }\n\n protected _root: TrieNode = new TrieNode('');\n\n /**\n * Get the root node.\n * @remarks Time O(1), Space O(1)\n * @returns Root TrieNode.\n */\n\n get root() {\n return this._root;\n }\n\n /**\n * (Protected) Get total count for base class iteration.\n * @remarks Time O(1), Space O(1)\n * @returns Total number of elements.\n */\n\n protected get _total() {\n return this._size;\n }\n\n /**\n * Insert one word into the trie.\n * @remarks Time O(L), Space O(L)\n * @param word - Word to insert.\n * @returns True if the word was newly added.\n */\n\n add(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n let isNewWord = false;\n for (const c of word) {\n let nodeC = cur.children.get(c);\n if (!nodeC) {\n nodeC = new TrieNode(c);\n cur.children.set(c, nodeC);\n }\n cur = nodeC;\n }\n if (!cur.isEnd) {\n isNewWord = true;\n cur.isEnd = true;\n this._size++;\n }\n return isNewWord;\n }\n\n /**\n * Insert many words from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param words - Iterable of strings (or raw records if toElementFn is provided).\n * @returns Array of per-word 'added' flags.\n */\n\n addMany(words: Iterable<string> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const word of words) {\n if (this.toElementFn) {\n ans.push(this.add(this.toElementFn(word as R)));\n } else {\n ans.push(this.add(word as string));\n }\n }\n return ans;\n }\n\n /**\n * Check whether a word exists.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to search for.\n * @returns True if present.\n */\n\n override has(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n for (const c of word) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return cur.isEnd;\n }\n\n /**\n * Check whether the trie is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Remove all words and reset to a fresh root.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._size = 0;\n this._root = new TrieNode('');\n }\n\n /**\n * Delete one word if present.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to delete.\n * @returns True if a word was removed.\n */\n\n delete(word: string): boolean {\n word = this._caseProcess(word);\n let isDeleted = false;\n const dfs = (cur: TrieNode, i: number): boolean => {\n const char = word[i];\n const child = cur.children.get(char);\n if (child) {\n if (i === word.length - 1) {\n if (child.isEnd) {\n if (child.children.size > 0) {\n child.isEnd = false;\n } else {\n cur.children.delete(char);\n }\n isDeleted = true;\n return true;\n }\n return false;\n }\n const res = dfs(child, i + 1);\n if (res && !cur.isEnd && child.children.size === 0) {\n cur.children.delete(char);\n return true;\n }\n return false;\n }\n return false;\n };\n\n dfs(this.root, 0);\n if (isDeleted) {\n this._size--;\n }\n return isDeleted;\n }\n\n /**\n * Compute the height (max depth) of the trie.\n * @remarks Time O(N), Space O(H)\n * @returns Maximum depth from root to a leaf.\n */\n\n getHeight(): number {\n const startNode = this.root;\n let maxDepth = 0;\n if (startNode) {\n const bfs = (node: TrieNode, level: number) => {\n if (level > maxDepth) {\n maxDepth = level;\n }\n const { children } = node;\n if (children) {\n for (const child of children.entries()) {\n bfs(child[1], level + 1);\n }\n }\n };\n bfs(startNode, 0);\n }\n return maxDepth;\n }\n\n /**\n * Check whether input is a proper prefix of at least one word.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input is a prefix but not a full word.\n */\n\n hasPurePrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return !cur.isEnd;\n }\n\n /**\n * Check whether any word starts with input.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input matches a path from root.\n */\n\n hasPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return true;\n }\n\n /**\n * Check whether the trie’s longest common prefix equals input.\n * @remarks Time O(min(H,L)), Space O(1)\n * @param input - Candidate longest common prefix.\n * @returns True if input equals the common prefix.\n */\n\n hasCommonPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (commonPre === input) return;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre === input;\n }\n\n /**\n * Return the longest common prefix among all words.\n * @remarks Time O(H), Space O(1)\n * @returns The longest common prefix string.\n */\n\n getLongestCommonPrefix(): string {\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre;\n }\n\n /**\n * Collect words under a prefix up to a maximum count.\n * @remarks Time O(K·L), Space O(K·L)\n * @param [prefix] - Prefix to match; default empty string for root.\n * @param [max] - Maximum number of words to return; default is Number.MAX_SAFE_INTEGER.\n * @param [isAllWhenEmptyPrefix] - When true, collect from root even if prefix is empty.\n * @returns Array of collected words (at most max).\n */\n\n getWords(prefix = '', max = Number.MAX_SAFE_INTEGER, isAllWhenEmptyPrefix = false): string[] {\n prefix = this._caseProcess(prefix);\n const words: string[] = [];\n let found = 0;\n\n function dfs(node: TrieNode, word: string) {\n for (const char of node.children.keys()) {\n const charNode = node.children.get(char);\n if (charNode !== undefined) {\n dfs(charNode, word.concat(char));\n }\n }\n if (node.isEnd) {\n if (found > max - 1) return;\n words.push(word);\n found++;\n }\n }\n\n let startNode = this.root;\n\n if (prefix) {\n for (const c of prefix) {\n const nodeC = startNode.children.get(c);\n if (nodeC) {\n startNode = nodeC;\n } else {\n return [];\n }\n }\n }\n\n if (isAllWhenEmptyPrefix || startNode !== this.root) dfs(startNode, prefix);\n\n return words;\n }\n\n /**\n * Deep clone this trie by iterating and inserting all words.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @returns A new trie with the same words and options.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this) next.add(x);\n return next;\n }\n\n /**\n * Filter words into a new trie of the same class.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param predicate - Predicate (word, index, trie) → boolean to keep word.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new trie containing words that satisfy the predicate.\n */\n\n filter(predicate: ElementCallback<string, R, boolean>, thisArg?: any): this {\n const results = this._createInstance();\n let index = 0;\n for (const word of this) {\n if (predicate.call(thisArg, word, index, this)) {\n results.add(word);\n }\n index++;\n }\n return results;\n }\n\n map<RM>(callback: ElementCallback<string, R, string>, options?: TrieOptions<RM>, thisArg?: any): Trie<RM>;\n\n /**\n * Map words into a new trie (possibly different record type).\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template EM\n * @template RM\n * @param callback - Mapping function (word, index, trie) → newWord (string).\n * @param [options] - Options for the output trie (e.g., toElementFn, caseSensitive).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Trie constructed from mapped words.\n */\n\n map<EM, RM>(\n callback: ElementCallback<string, R, EM>,\n options?: TrieOptions<RM>,\n thisArg?: any\n ): IterableElementBase<EM, RM>;\n\n map<EM, RM>(callback: ElementCallback<string, R, EM>, options?: TrieOptions<RM>, thisArg?: any): any {\n const newTrie = this._createLike<RM>([], options);\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n if (typeof v !== 'string') {\n throw new TypeError(`Trie.map callback must return string; got ${typeof v}`);\n }\n newTrie.add(v);\n }\n return newTrie;\n }\n\n /**\n * Map words into a new trie of the same element type.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param callback - Mapping function (word, index, trie) → string.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new trie with mapped words.\n */\n\n mapSame(callback: ElementCallback<string, R, string>, thisArg?: any): this {\n const next = this._createInstance();\n let i = 0;\n for (const key of this) {\n const mapped = thisArg === undefined ? callback(key, i++, this) : callback.call(thisArg, key, i++, this);\n next.add(mapped);\n }\n return next;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind trie instance.\n */\n\n protected _createInstance(options?: TrieOptions<R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], {\n toElementFn: this.toElementFn,\n caseSensitive: this.caseSensitive,\n ...(options ?? {})\n });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind trie and seed it from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template RM\n * @param [elements] - Iterable used to seed the new trie.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Trie instance.\n */\n\n protected _createLike<RM>(elements: Iterable<string> | Iterable<RM> = [], options?: TrieOptions<RM>): Trie<RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Trie<RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind trie instance.\n * @remarks Time O(1), Space O(1)\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind Trie instance.\n */\n\n protected _spawnLike<RM>(options?: TrieOptions<RM>): Trie<RM> {\n return this._createLike<RM>([], options);\n }\n\n /**\n * (Protected) Iterate all words in lexicographic order of edges.\n * @remarks Time O(ΣL), Space O(H)\n * @returns Iterator of words.\n */\n\n protected *_getIterator(): IterableIterator<string> {\n function* _dfs(node: TrieNode, path: string): IterableIterator<string> {\n if (node.isEnd) {\n yield path;\n }\n for (const [char, childNode] of node.children) {\n yield* _dfs(childNode, path + char);\n }\n }\n\n yield* _dfs(this.root, '');\n }\n\n /**\n * (Protected) Normalize a string according to case sensitivity.\n * @remarks Time O(L), Space O(L)\n * @param str - Input string to normalize.\n * @returns Normalized string based on caseSensitive.\n */\n\n protected _caseProcess(str: string) {\n if (!this._caseSensitive) {\n str = str.toLowerCase();\n }\n return str;\n }\n}\n","export class TreeNode<V = any> {\n /**\n * The constructor function initializes a TreeNode object with a key, optional value, and optional\n * children.\n * @param {string} key - A string representing the key of the tree node.\n * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the\n * value associated with the node. If no value is provided, it defaults to `undefined`.\n * @param {TreeNode<V>[]} [children] - The `children` parameter is an optional array of `TreeNode<V>`\n * objects. It represents the child nodes of the current node. If no children are provided, the\n * default value is an empty array.\n */\n constructor(key: string, value?: V, children?: TreeNode<V>[]) {\n this._key = key;\n this._value = value || undefined;\n if (children) this._children = children;\n }\n\n protected _key: string;\n\n /**\n * The function returns the value of the protected variable _key.\n * @returns The value of the `_key` property, which is a string.\n */\n get key(): string {\n return this._key;\n }\n\n /**\n * The above function sets the value of a protected variable called \"key\".\n * @param {string} value - The value parameter is a string that represents the value to be assigned\n * to the key.\n */\n set key(value: string) {\n this._key = value;\n }\n\n protected _value?: V | undefined;\n\n /**\n * The function returns the value stored in a variable, or undefined if the variable is empty.\n * @returns The value of the variable `_value` is being returned.\n */\n get value(): V | undefined {\n return this._value;\n }\n\n /**\n * The function sets the value of a variable.\n * @param {V | undefined} value - The parameter \"value\" is of type \"V | undefined\", which means it\n * can accept a value of type \"V\" or it can be undefined.\n */\n set value(value: V | undefined) {\n this._value = value;\n }\n\n protected _children?: TreeNode<V>[] | undefined;\n\n /**\n * The function returns an array of TreeNode objects or undefined.\n * @returns The `children` property is being returned. It is of type `TreeNode<V>[] | undefined`,\n * which means it can either be an array of `TreeNode<V>` objects or `undefined`.\n */\n get children(): TreeNode<V>[] | undefined {\n return this._children;\n }\n\n /**\n * The function sets the value of the children property of a TreeNode object.\n * @param {TreeNode<V>[] | undefined} value - The value parameter is of type TreeNode<V>[] |\n * undefined. This means that it can accept an array of TreeNode objects or undefined.\n */\n set children(value: TreeNode<V>[] | undefined) {\n this._children = value;\n }\n\n /**\n * The function `addChildren` adds one or more child nodes to the current node.\n * @param {TreeNode<V> | TreeNode<V>[]} children - The `children` parameter can be either a single\n * `TreeNode<V>` object or an array of `TreeNode<V>` objects.\n */\n addChildren(children: TreeNode<V> | TreeNode<V>[]) {\n if (!this._children) {\n this._children = [];\n }\n if (children instanceof TreeNode) {\n this._children.push(children);\n } else {\n this._children = this._children.concat(children);\n }\n }\n\n /**\n * The function `getHeight()` calculates the maximum depth of a tree structure by performing a\n * breadth-first search.\n * @returns the maximum depth or height of the tree.\n */\n getHeight() {\n let maxDepth = 0;\n if (this) {\n const bfs = (node: TreeNode<V>, level: number) => {\n if (level > maxDepth) {\n maxDepth = level;\n }\n const { _children } = node;\n if (_children) {\n for (let i = 0, len = _children.length; i < len; i++) {\n bfs(_children[i], level + 1);\n }\n }\n };\n bfs(this, 0);\n }\n return maxDepth;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,MAAe,o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