typescript-dsa-stl 2.7.0 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +217 -67
- package/dist/algorithms/graph.d.ts +49 -0
- package/dist/algorithms/graph.d.ts.map +1 -1
- package/dist/algorithms/graph.js +95 -0
- package/dist/algorithms/graph.js.map +1 -1
- package/dist/algorithms/index.d.ts +3 -2
- package/dist/algorithms/index.d.ts.map +1 -1
- package/dist/algorithms/index.js +2 -1
- package/dist/algorithms/index.js.map +1 -1
- package/dist/algorithms/trie.d.ts +23 -0
- package/dist/algorithms/trie.d.ts.map +1 -0
- package/dist/algorithms/trie.js +80 -0
- package/dist/algorithms/trie.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**Repository** for the npm package **[typescript-dsa-stl](https://www.npmjs.com/package/typescript-dsa-stl)** · [GitHub](https://github.com/SajidAbdullah729/TypeScript_DSA)
|
|
4
4
|
|
|
5
|
-
STL-style data structures and algorithms for TypeScript: **Vector**, **Stack**, **Queue**, **Deque**, **List**, **PriorityQueue**, ordered/unordered **Map** and **Set**, **OrderedMultiMap** / **OrderedMultiSet**, **segment trees**, **graph** helpers (BFS, DFS, Dijkstra, Kruskal, DSU), and **string** algorithms (KMP, Rabin–Karp, rolling hash). Install from npm for your app; this repo is the source.
|
|
5
|
+
STL-style data structures and algorithms for TypeScript: **Vector**, **Stack**, **Queue**, **Deque**, **List**, **PriorityQueue**, ordered/unordered **Map** and **Set**, **OrderedMultiMap** / **OrderedMultiSet**, **segment trees**, **graph** helpers (BFS, DFS, topological sort, Dijkstra, Kruskal, DSU), and **string** algorithms (KMP, Rabin–Karp, rolling hash). Install from npm for your app; this repo is the source.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -14,11 +14,11 @@ STL-style data structures and algorithms for TypeScript: **Vector**, **Stack**,
|
|
|
14
14
|
| [Package layout & imports](#package-layout--imports) | Barrel vs subpaths (tree-shaking) |
|
|
15
15
|
| [Quick start](#quick-start) | One file showing main APIs |
|
|
16
16
|
| [API reference](#api-reference) | Export tables |
|
|
17
|
-
| [Complexity](#complexity) | Big-O for collections
|
|
17
|
+
| [Complexity](#complexity) | Big-O for collections |
|
|
18
18
|
| [Collections](#collections) | Deque, nested vectors, multi-map / multi-set |
|
|
19
|
-
| [Segment trees](#segment-trees) |
|
|
20
|
-
| [Graph algorithms](#graph-algorithms) | Adjacency lists, BFS/DFS, components, MST, shortest paths |
|
|
21
|
-
| [String algorithms](#string-algorithms) | KMP, Rabin–Karp, rolling hash |
|
|
19
|
+
| [Segment trees](#segment-trees) | Overview, variants, and examples (one section) |
|
|
20
|
+
| [Graph algorithms](#graph-algorithms) | Adjacency lists, BFS/DFS, topological sort, components, MST, shortest paths |
|
|
21
|
+
| [String algorithms](#string-algorithms) | KMP, Rabin–Karp, Trie, rolling hash |
|
|
22
22
|
| [For maintainers](#for-maintainers) | Build and publish |
|
|
23
23
|
| [License](#license) | MIT |
|
|
24
24
|
|
|
@@ -45,8 +45,11 @@ import {
|
|
|
45
45
|
binarySearch,
|
|
46
46
|
breadthFirstSearch,
|
|
47
47
|
depthFirstSearch,
|
|
48
|
+
topologicalSortStack,
|
|
49
|
+
topologicalSortIndegree,
|
|
48
50
|
KnuthMorrisPratt,
|
|
49
51
|
RabinKarp,
|
|
52
|
+
Trie,
|
|
50
53
|
StringRollingHash,
|
|
51
54
|
} from 'typescript-dsa-stl/algorithms';
|
|
52
55
|
import { clamp, range } from 'typescript-dsa-stl/utils';
|
|
@@ -164,15 +167,15 @@ range(0, 5); // [0, 1, 2, 3, 4]
|
|
|
164
167
|
| Area | Exports |
|
|
165
168
|
|------|---------|
|
|
166
169
|
| **Collections** | `Vector`, `Stack`, `Queue`, `Deque`, `List`, `ListNode`, `PriorityQueue`, `OrderedMap`, `UnorderedMap`, `OrderedSet`, `UnorderedSet`, `OrderedMultiMap`, `OrderedMultiSet`, `GeneralSegmentTree`, `SegmentTree`, `SegmentTreeSum`, `SegmentTreeMin`, `SegmentTreeMax`, `LazySegmentTreeSum`, `WeightedEdge`, `AdjacencyList`, `WeightedAdjacencyList`, `createAdjacencyList`, `createWeightedAdjacencyList`, `addEdge`, `deleteEdge` |
|
|
167
|
-
| **Algorithms** | `sort`, `find`, `findIndex`, `transform`, `filter`, `reduce`, `reverse`, `unique`, `binarySearch`, `lowerBound`, `upperBound`, `min`, `max`, `partition`, `DisjointSetUnion`, `KnuthMorrisPratt`, `RabinKarp`, `RABIN_KARP_DEFAULT_MODS`, `StringRollingHash`, `breadthFirstSearch`, `depthFirstSearch`, `connectedComponents`, `kruskalMST`, `dijkstra`, `reconstructPath` |
|
|
170
|
+
| **Algorithms** | `sort`, `find`, `findIndex`, `transform`, `filter`, `reduce`, `reverse`, `unique`, `binarySearch`, `lowerBound`, `upperBound`, `min`, `max`, `partition`, `DisjointSetUnion`, `KnuthMorrisPratt`, `RabinKarp`, `Trie`, `RABIN_KARP_DEFAULT_MODS`, `StringRollingHash`, `breadthFirstSearch`, `depthFirstSearch`, `topologicalSortStack`, `topologicalSortIndegree`, `connectedComponents`, `kruskalMST`, `dijkstra`, `reconstructPath` |
|
|
168
171
|
| **Utils** | `clamp`, `range`, `noop`, `identity`, `swap` |
|
|
169
|
-
| **Types** | `Comparator`, `Predicate`, `UnaryFn`, `Reducer`, `IterableLike`, `toArray`, `RabinKarpTripleMods`, `WeightedUndirectedEdge`, `GeneralSegmentTreeConfig`, `SegmentCombine`, `SegmentMerge`, `SegmentLeafBuild` |
|
|
172
|
+
| **Types** | `Comparator`, `Predicate`, `UnaryFn`, `Reducer`, `IterableLike`, `toArray`, `RabinKarpTripleMods`, `WeightedUndirectedEdge`, `TopologicalSortResult`, `GeneralSegmentTreeConfig`, `SegmentCombine`, `SegmentMerge`, `SegmentLeafBuild` |
|
|
170
173
|
|
|
171
174
|
### Subpath imports (tree-shaking)
|
|
172
175
|
|
|
173
176
|
```ts
|
|
174
177
|
import { Vector, Stack, Queue, Deque } from 'typescript-dsa-stl/collections';
|
|
175
|
-
import { sort, binarySearch, breadthFirstSearch, depthFirstSearch, KnuthMorrisPratt, RabinKarp, StringRollingHash } from 'typescript-dsa-stl/algorithms';
|
|
178
|
+
import { sort, binarySearch, breadthFirstSearch, depthFirstSearch, topologicalSortStack, topologicalSortIndegree, KnuthMorrisPratt, RabinKarp, Trie, StringRollingHash } from 'typescript-dsa-stl/algorithms';
|
|
176
179
|
import { clamp, range } from 'typescript-dsa-stl/utils';
|
|
177
180
|
import type { Comparator } from 'typescript-dsa-stl/types';
|
|
178
181
|
```
|
|
@@ -201,12 +204,7 @@ import type { Comparator } from 'typescript-dsa-stl/types';
|
|
|
201
204
|
\* Amortized (hash).
|
|
202
205
|
\** At a known node.
|
|
203
206
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
| Structure | Build | Point update | Range query | Extra |
|
|
207
|
-
|-----------|-------|--------------|-------------|--------|
|
|
208
|
-
| **GeneralSegmentTree**, **SegmentTree**, **SegmentTreeSum** / **Min** / **Max** | O(n) | O(log n) | O(log n) | Inclusive `[l, r]`; **GeneralSegmentTree** keeps raw `V` and uses `merge` + `buildLeaf` |
|
|
209
|
-
| **LazySegmentTreeSum** | O(n) | `set`: O(log n) | `rangeSum`: O(log n) | `rangeAdd` on a range: O(log n) |
|
|
207
|
+
Segment-tree time and space behaviour is documented in [Segment trees](#segment-trees) (overview and table at the start of that section).
|
|
210
208
|
|
|
211
209
|
---
|
|
212
210
|
|
|
@@ -330,9 +328,33 @@ for (const [key, value] of index) {
|
|
|
330
328
|
|
|
331
329
|
## Segment trees
|
|
332
330
|
|
|
331
|
+
### Segment tree overview and complexity
|
|
332
|
+
|
|
333
|
+
A segment tree is an indexable array backed by a tree so **range questions** (sum, min, max, or your own combine) and **updates** cost **O(log n)** instead of scanning the whole slice.
|
|
334
|
+
|
|
333
335
|
Segment trees support **range queries** and **point updates** in **O(log n)**. Range endpoints are **inclusive**: `query(l, r)` covers indices `l` through `r`.
|
|
334
336
|
|
|
335
|
-
|
|
337
|
+
**What each type does:**
|
|
338
|
+
|
|
339
|
+
| Type | Does |
|
|
340
|
+
|------|------|
|
|
341
|
+
| **SegmentTreeSum** / **Min** / **Max** | Fixed numeric range **sum**, **min**, or **max** with **one index updated at a time**. |
|
|
342
|
+
| **SegmentTree** (generic) | Your own **associative** combine over ranges; same type for array entries and node values. |
|
|
343
|
+
| **GeneralSegmentTree** | Array stores raw **V**, nodes hold a summary **T** built with **merge** and **buildLeaf**. |
|
|
344
|
+
| **LazySegmentTreeSum** | **Add the same delta to a whole range**, optional **single-cell set**, and **range sum** (lazy tags). |
|
|
345
|
+
|
|
346
|
+
| Structure | Build | Point update | Range query | Extra |
|
|
347
|
+
|-----------|-------|--------------|-------------|--------|
|
|
348
|
+
| **GeneralSegmentTree**, **SegmentTree**, **SegmentTreeSum** / **Min** / **Max** | O(n) | O(log n) | O(log n) | Inclusive `[l, r]`; **GeneralSegmentTree** keeps raw `V` and uses `merge` + `buildLeaf` |
|
|
349
|
+
| **LazySegmentTreeSum** | O(n) | `set`: O(log n) | `rangeSum`: O(log n) | `rangeAdd` on a range: O(log n) |
|
|
350
|
+
|
|
351
|
+
### Segment tree: Sum, Min, Max and example
|
|
352
|
+
|
|
353
|
+
- **`SegmentTreeSum`** — answers “what is the **sum** from `l` to `r`?” after you **`update(i, value)`** on one index.
|
|
354
|
+
- **`SegmentTreeMin`** — answers “what is the **minimum** in `[l, r]`?” after single-index updates.
|
|
355
|
+
- **`SegmentTreeMax`** — answers “what is the **maximum** in `[l, r]`?” after single-index updates.
|
|
356
|
+
|
|
357
|
+
Together they are fixed numeric implementations: build from initial values, **`update(i, value)`** for one index, **`query(l, r)`** for an inclusive range.
|
|
336
358
|
|
|
337
359
|
```ts
|
|
338
360
|
import {
|
|
@@ -353,9 +375,41 @@ const mx = new SegmentTreeMax([5, 2, 8, 1]);
|
|
|
353
375
|
console.log(mx.query(0, 3)); // 8
|
|
354
376
|
```
|
|
355
377
|
|
|
356
|
-
|
|
378
|
+
**Example — analytics / reporting (fixed buckets, range totals, single-day corrections):** each index is a **fixed bucket** (hour, day, version slot, …). You ask for the **sum** from bucket `a` through `b` and sometimes **fix one bucket** after late data or reconciliation — same API as above, wrapped for clarity.
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
import { SegmentTreeSum } from 'typescript-dsa-stl';
|
|
382
|
+
|
|
383
|
+
/** Revenue (or events, page views, API calls) per calendar day; index 0 = first day of period. */
|
|
384
|
+
class PeriodMetrics {
|
|
385
|
+
private readonly tree: SegmentTreeSum;
|
|
357
386
|
|
|
358
|
-
|
|
387
|
+
constructor(dailyValues: readonly number[]) {
|
|
388
|
+
this.tree = new SegmentTreeSum(dailyValues);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Total for an inclusive day range — e.g. chart drill-down or export row. */
|
|
392
|
+
totalBetweenDay(firstDayIndex: number, lastDayIndex: number): number {
|
|
393
|
+
return this.tree.query(firstDayIndex, lastDayIndex);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Backfill or correct one day without rebuilding the whole series. */
|
|
397
|
+
setDay(dayIndex: number, amount: number): void {
|
|
398
|
+
this.tree.update(dayIndex, amount);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const january = new PeriodMetrics([1200, 980, 1100, 1050, 1300]);
|
|
403
|
+
console.log(january.totalBetweenDay(0, 4)); // full period
|
|
404
|
+
january.setDay(2, 1150); // corrected day 2
|
|
405
|
+
console.log(january.totalBetweenDay(1, 3)); // sum over days 1..3
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
In production you would usually **persist** the underlying series in a database and **rebuild** the tree when the period reloads; the tree stays useful in memory for dashboards, simulations, or request handlers that see heavy read/update traffic on the same window.
|
|
409
|
+
|
|
410
|
+
### Generic SegmentTree
|
|
411
|
+
|
|
412
|
+
**`SegmentTree<T>`** supports range queries for **any associative operation** (gcd, concatenation, bitwise OR, …) on a fixed-length array, with **point updates**, when element type and aggregate type are the same — pass an **associative** `combine` and a **neutral** value for query ranges that miss a segment (e.g. `0` for sum, `Infinity` for min).
|
|
359
413
|
|
|
360
414
|
```ts
|
|
361
415
|
import { SegmentTree } from 'typescript-dsa-stl';
|
|
@@ -385,9 +439,11 @@ const strTree = new SegmentTree<string>(
|
|
|
385
439
|
console.log(strTree.query(0, 2)); // 'abc'
|
|
386
440
|
```
|
|
387
441
|
|
|
388
|
-
###
|
|
442
|
+
### GeneralSegmentTree
|
|
443
|
+
|
|
444
|
+
**`GeneralSegmentTree<T, V>`** keeps **raw** values of type **V** in the array while each segment stores a **different** summary type **T** (e.g. raw numbers in the array, but nodes keep sums of squares or custom stats).
|
|
389
445
|
|
|
390
|
-
|
|
446
|
+
You supply:
|
|
391
447
|
|
|
392
448
|
- **`merge(left, right)`** — combine two child aggregates (internal nodes).
|
|
393
449
|
- **`neutral`** — identity for `merge` when a query does not overlap a segment.
|
|
@@ -407,9 +463,11 @@ st.update(1, 4);
|
|
|
407
463
|
console.log(st.rawAt(1)); // 4 — current raw value at index 1
|
|
408
464
|
```
|
|
409
465
|
|
|
410
|
-
###
|
|
466
|
+
### LazySegmentTreeSum and example
|
|
467
|
+
|
|
468
|
+
**`LazySegmentTreeSum`** maintains a numeric array where you can **add a constant to every element in a range**, **overwrite one cell**, and query **range sums** — all in **O(log n)** via lazy propagation (unlike the trees above, which only support point updates).
|
|
411
469
|
|
|
412
|
-
**`rangeAdd(l, r, delta)`** adds `delta` to every element in the inclusive range. **`rangeSum(l, r)`** returns the sum. **`set(i, value)`** assigns one position (lazy tags are applied along the path). All are **O(log n)
|
|
470
|
+
**`rangeAdd(l, r, delta)`** adds `delta` to every element in the inclusive range. **`rangeSum(l, r)`** returns the sum. **`set(i, value)`** assigns one position (lazy tags are applied along the path). All are **O(log n)** — see the complexity table in the overview above.
|
|
413
471
|
|
|
414
472
|
```ts
|
|
415
473
|
import { LazySegmentTreeSum } from 'typescript-dsa-stl';
|
|
@@ -421,47 +479,7 @@ lazy.set(0, 100);
|
|
|
421
479
|
console.log(lazy.rangeSum(0, 3)); // 100 + 5 + 5 + 0
|
|
422
480
|
```
|
|
423
481
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
These patterns show up in backends and internal tools when you need **many** range queries and updates on a fixed sequence (length known up front), without scanning the whole array each time.
|
|
427
|
-
|
|
428
|
-
#### 1. Analytics or reporting: totals over a time window (with corrections)
|
|
429
|
-
|
|
430
|
-
Each index is a **fixed bucket** (hour of day, day of month, version slot, etc.). You repeatedly ask “what is the **sum** from bucket `a` through `b`?” and sometimes **fix one bucket** after late data or a reconciliation.
|
|
431
|
-
|
|
432
|
-
```ts
|
|
433
|
-
import { SegmentTreeSum } from 'typescript-dsa-stl';
|
|
434
|
-
|
|
435
|
-
/** Revenue (or events, page views, API calls) per calendar day; index 0 = first day of period. */
|
|
436
|
-
class PeriodMetrics {
|
|
437
|
-
private readonly tree: SegmentTreeSum;
|
|
438
|
-
|
|
439
|
-
constructor(dailyValues: readonly number[]) {
|
|
440
|
-
this.tree = new SegmentTreeSum(dailyValues);
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
/** Total for an inclusive day range — e.g. chart drill-down or export row. */
|
|
444
|
-
totalBetweenDay(firstDayIndex: number, lastDayIndex: number): number {
|
|
445
|
-
return this.tree.query(firstDayIndex, lastDayIndex);
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
/** Backfill or correct one day without rebuilding the whole series. */
|
|
449
|
-
setDay(dayIndex: number, amount: number): void {
|
|
450
|
-
this.tree.update(dayIndex, amount);
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
const january = new PeriodMetrics([1200, 980, 1100, 1050, 1300]);
|
|
455
|
-
console.log(january.totalBetweenDay(0, 4)); // full period
|
|
456
|
-
january.setDay(2, 1150); // corrected day 2
|
|
457
|
-
console.log(january.totalBetweenDay(1, 3)); // sum over days 1..3
|
|
458
|
-
```
|
|
459
|
-
|
|
460
|
-
In production you would usually **persist** the underlying series in a database and **rebuild** the tree when the period reloads; the tree stays useful in memory for dashboards, simulations, or request handlers that see heavy read/update traffic on the same window.
|
|
461
|
-
|
|
462
|
-
#### 2. Operations or finance: bulk adjustment on a slice, then aggregate
|
|
463
|
-
|
|
464
|
-
You apply the **same delta** to **every** element in an index range (tiered bonuses, prorated credits, simulation shocks), then need **range sums** for reporting. A lazy sum tree avoids touching each cell one by one.
|
|
482
|
+
**Example — bulk adjustment on a slice, then aggregate:** apply the **same delta** to **every** element in an index range (bonuses, prorated credits, simulation shocks), then query **range sums** without updating each cell one by one.
|
|
465
483
|
|
|
466
484
|
```ts
|
|
467
485
|
import { LazySegmentTreeSum } from 'typescript-dsa-stl';
|
|
@@ -646,6 +664,117 @@ console.log(breadthFirstSearch(5, withIsolated, 0)); // [0, 1] — not [0,1,2,3,
|
|
|
646
664
|
- **Disconnected graphs:** run again from another unvisited `start`, or use `connectedComponents` to enumerate components first.
|
|
647
665
|
- **Weighted graphs:** for traversal ignoring weights, use the same vertex lists as the unweighted graph (weights are ignored by these two functions).
|
|
648
666
|
|
|
667
|
+
### Topological sort
|
|
668
|
+
|
|
669
|
+
`topologicalSortStack` (iterative DFS / finish order) and `topologicalSortIndegree` (Kahn’s algorithm, zero-indegree queue) both take `n` and a **directed** unweighted `AdjacencyList`. They return `{ order, ok }`: a permutation of `0..n-1` when `ok` is true, or failure when a directed cycle exists.
|
|
670
|
+
|
|
671
|
+
**When to use**
|
|
672
|
+
|
|
673
|
+
- **Task / build / dependency ordering:** items must happen only after their prerequisites (package install order, compile steps, course prerequisites).
|
|
674
|
+
- **Scheduling under precedence constraints:** jobs with “A before B” rules and no cycles.
|
|
675
|
+
- **Detecting cycles in a directed model:** if `ok` is false, the graph (on valid vertices `0..n-1`) is not a DAG.
|
|
676
|
+
- **Pick either algorithm:** both answer the same yes/no; choose **stack** if you want DFS-style behavior and an explicit stack; choose **indegree** (Kahn) if you prefer peeling sources level-by-level (often closer to “ready queue” mental models).
|
|
677
|
+
|
|
678
|
+
**When topological order is not possible**
|
|
679
|
+
|
|
680
|
+
- Any **directed cycle** (including a **self-loop**): `ok` is false.
|
|
681
|
+
- **Undirected** graphs modeled with **both** `u → v` and `v → u`: that is a 2-cycle, so **not** a DAG unless you only use directed edges that reflect real precedence.
|
|
682
|
+
|
|
683
|
+
**Example (how to call it and use the result)**
|
|
684
|
+
|
|
685
|
+
Both functions return the same shape: **`TopologicalSortResult`** — `{ order: number[]; ok: boolean }`.
|
|
686
|
+
|
|
687
|
+
- **`ok === true`:** `order` is a **permutation of `0..n-1`**; every edge `u → v` appears with `u` before `v` in `order`.
|
|
688
|
+
- **`ok === false`:** **no** full topological order exists (directed cycle). For `topologicalSortStack`, `order` is `[]`. For `topologicalSortIndegree`, `order` may list only some vertices; **do not** treat it as a complete sort.
|
|
689
|
+
|
|
690
|
+
```ts
|
|
691
|
+
import {
|
|
692
|
+
createAdjacencyList,
|
|
693
|
+
addEdge,
|
|
694
|
+
topologicalSortStack,
|
|
695
|
+
topologicalSortIndegree,
|
|
696
|
+
type TopologicalSortResult,
|
|
697
|
+
} from 'typescript-dsa-stl';
|
|
698
|
+
|
|
699
|
+
const n = 4;
|
|
700
|
+
const g = createAdjacencyList(n);
|
|
701
|
+
addEdge(g, 0, 1);
|
|
702
|
+
addEdge(g, 0, 2);
|
|
703
|
+
addEdge(g, 1, 3);
|
|
704
|
+
addEdge(g, 2, 3);
|
|
705
|
+
|
|
706
|
+
// Whole result (typed)
|
|
707
|
+
const result: TopologicalSortResult = topologicalSortStack(n, g);
|
|
708
|
+
|
|
709
|
+
// Usually destructure
|
|
710
|
+
const { order, ok } = topologicalSortIndegree(n, g);
|
|
711
|
+
|
|
712
|
+
if (ok) {
|
|
713
|
+
// `order` here is from `topologicalSortIndegree` above → [0, 1, 2, 3] for this graph.
|
|
714
|
+
|
|
715
|
+
// 1) See the whole sequence at once
|
|
716
|
+
console.log(order);
|
|
717
|
+
// → [ 0, 1, 2, 3 ] (Node.js / browser consoles may add line breaks or “Array(4)” styling)
|
|
718
|
+
|
|
719
|
+
// 2) How many steps (same as n when ok is true)
|
|
720
|
+
console.log(order.length);
|
|
721
|
+
// → 4
|
|
722
|
+
|
|
723
|
+
// 3) Pick by position: first task, second task, …
|
|
724
|
+
const first = order[0];
|
|
725
|
+
const second = order[1];
|
|
726
|
+
console.log('do vertex', first, 'before', second);
|
|
727
|
+
// → do vertex 0 before 1
|
|
728
|
+
|
|
729
|
+
// 4) Simple loop with indices
|
|
730
|
+
for (let i = 0; i < order.length; i++) {
|
|
731
|
+
console.log('step', i + 1, '→ vertex', order[i]);
|
|
732
|
+
}
|
|
733
|
+
// → step 1 → vertex 0
|
|
734
|
+
// → step 2 → vertex 1
|
|
735
|
+
// → step 3 → vertex 2
|
|
736
|
+
// → step 4 → vertex 3
|
|
737
|
+
|
|
738
|
+
// 5) Same loop, shorter (when you only need the vertex id)
|
|
739
|
+
for (const vertex of order) {
|
|
740
|
+
console.log('run job for vertex', vertex);
|
|
741
|
+
}
|
|
742
|
+
// → run job for vertex 0
|
|
743
|
+
// → run job for vertex 1
|
|
744
|
+
// → run job for vertex 2
|
|
745
|
+
// → run job for vertex 3
|
|
746
|
+
|
|
747
|
+
// 6) Optional: each number is an index into your own list of names
|
|
748
|
+
const jobNames = ['bootstrap', 'compileA', 'compileB', 'link'];
|
|
749
|
+
const readable = order.map((vertex) => jobNames[vertex]);
|
|
750
|
+
console.log(readable.join(' → '));
|
|
751
|
+
// → bootstrap → compileA → compileB → link
|
|
752
|
+
} else {
|
|
753
|
+
// No valid order exists (cycle). Use a flag, return early, or show an error.
|
|
754
|
+
console.error('Graph has a cycle; cannot topologically sort.');
|
|
755
|
+
// → Graph has a cycle; cannot topologically sort.
|
|
756
|
+
// (often printed on stderr; some runtimes prepend “Error” styling)
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// Compare algorithms (same `ok` on a given graph; `order` may differ)
|
|
760
|
+
const a = topologicalSortStack(n, g);
|
|
761
|
+
const b = topologicalSortIndegree(n, g);
|
|
762
|
+
console.log(a.ok, b.ok);
|
|
763
|
+
// → true true
|
|
764
|
+
// (here `a.order` is [0, 2, 1, 3] and `b.order` is [0, 1, 2, 3] — both valid)
|
|
765
|
+
|
|
766
|
+
// Cycle: 0 → 1 → 2 → 0
|
|
767
|
+
const cyclic = createAdjacencyList(3);
|
|
768
|
+
addEdge(cyclic, 0, 1);
|
|
769
|
+
addEdge(cyclic, 1, 2);
|
|
770
|
+
addEdge(cyclic, 2, 0);
|
|
771
|
+
const bad = topologicalSortStack(3, cyclic);
|
|
772
|
+
console.log(bad.ok);
|
|
773
|
+
// → false
|
|
774
|
+
console.log(bad.order);
|
|
775
|
+
// → []
|
|
776
|
+
```
|
|
777
|
+
|
|
649
778
|
### Disjoint Set Union (Union-Find)
|
|
650
779
|
|
|
651
780
|
Use Union-Find (DSU) to compute connected components efficiently. It merges endpoints of every edge in the adjacency list, so for directed graphs it returns weak connectivity components.
|
|
@@ -762,9 +891,9 @@ console.log(path); // [0, 1, 2, 4]
|
|
|
762
891
|
|
|
763
892
|
## String algorithms
|
|
764
893
|
|
|
765
|
-
### Knuth–Morris–Pratt (KMP), Rabin–Karp, and string rolling hash
|
|
894
|
+
### Knuth–Morris–Pratt (KMP), Rabin–Karp, Trie, and string rolling hash
|
|
766
895
|
|
|
767
|
-
All
|
|
896
|
+
All four work on **UTF-16 code units** (same as `String` indexing). KMP and Rabin–Karp are **pattern matchers** (list all start indices of a pattern in a text). `Trie` is a **prefix tree** for fast dictionary operations (`insert`, exact word lookup, prefix lookup, deletion). `StringRollingHash` is a **substring-hash tool** on a **fixed** string—you combine it with your own logic (equality checks, binary search, etc.).
|
|
768
897
|
|
|
769
898
|
#### When to use which
|
|
770
899
|
|
|
@@ -772,16 +901,18 @@ All three work on **UTF-16 code units** (same as `String` indexing). They solve
|
|
|
772
901
|
|------|--------|-----|
|
|
773
902
|
| **Find every occurrence** of **one pattern** in **one text**, with **worst-case** O(n + m), **no hashing**, predictable behaviour | **KnuthMorrisPratt** | LPS table; only character comparisons; no modular arithmetic. |
|
|
774
903
|
| **Find every occurrence** of a pattern using a **sliding window** and **hashes** (triple moduli + final verify) | **RabinKarp** | Same asymptotic average case; good when you think in rolling hashes or batch **same-length** patterns. |
|
|
904
|
+
| **Maintain a dynamic dictionary** of words and answer **exact / prefix** queries efficiently | **Trie** | Insert/search/prefix in O(L) where L is key length; natural fit for autocomplete and prefix filtering. |
|
|
775
905
|
| **Many O(1) hash queries** on **substrings of one string** you already hold (compare two ranges, palindrome / LCP style checks, rolling checks without slicing) | **StringRollingHash** | O(n) preprocess, O(1) per `substringHash`; **not** a drop-in “find all matches” API—use KMP or Rabin–Karp for that. |
|
|
776
906
|
|
|
777
907
|
**Concrete situations**
|
|
778
908
|
|
|
779
909
|
- **Use KMP** when you need a **guaranteed** linear scan (interviews, strict time bounds, large alphabets), or the pattern is **reused** across many searches (`new KnuthMorrisPratt(pattern)` once, `.search(text)` many times).
|
|
780
910
|
- **Use Rabin–Karp** when a **rolling hash** model fits (e.g. one long stream, one pattern), or you later generalize to **several patterns of the same length** (compare each pattern’s triple hash to each window hash). Triple hashing keeps false hash positives negligible; **verification** still guarantees correct indices.
|
|
911
|
+
- **Use `Trie`** when your workload is dictionary-like: store many words once, then do repeated `search(word)` and `startsWith(prefix)` checks in **O(L)**.
|
|
781
912
|
- **Use `StringRollingHash`** when the problem is **“hash of s[l..r)”** many times on **one** `s`—e.g. check `s[i..i+k) === s[j..j+k)` via hash equality (then confirm if needed), or algorithms that **binary search** on length using substring hashes. For **only** “list all starts of P in T”, pick **KMP** or **Rabin–Karp** instead of building substring hashes by hand.
|
|
782
913
|
|
|
783
914
|
```ts
|
|
784
|
-
import { KnuthMorrisPratt, RabinKarp, StringRollingHash } from 'typescript-dsa-stl';
|
|
915
|
+
import { KnuthMorrisPratt, RabinKarp, Trie, StringRollingHash } from 'typescript-dsa-stl';
|
|
785
916
|
|
|
786
917
|
// A) Pattern fixed, searched in many buffers — build KMP once, call .search() repeatedly (LPS reused).
|
|
787
918
|
const multiDoc = new KnuthMorrisPratt('ERROR');
|
|
@@ -793,7 +924,15 @@ const hay = '...long text...';
|
|
|
793
924
|
KnuthMorrisPratt.findOccurrences(hay, 'needle');
|
|
794
925
|
new RabinKarp('needle').search(hay);
|
|
795
926
|
|
|
796
|
-
// C)
|
|
927
|
+
// C) Dictionary/prefix queries — Trie.
|
|
928
|
+
const trie = new Trie();
|
|
929
|
+
trie.insert('apple');
|
|
930
|
+
trie.insert('app');
|
|
931
|
+
trie.search('app'); // true
|
|
932
|
+
trie.startsWith('appl'); // true
|
|
933
|
+
trie.delete('app'); // true
|
|
934
|
+
|
|
935
|
+
// D) Same static string, many range-equality checks — rolling hash (not for “find all pattern starts” by itself).
|
|
797
936
|
const s = 'banana';
|
|
798
937
|
const rh = new StringRollingHash(s);
|
|
799
938
|
// Does s[1..4) equal s[3..6)? (both length 3)
|
|
@@ -809,8 +948,9 @@ const maybe = rh.substringHash(1, 3) === rh.substringHash(3, 3); // then compare
|
|
|
809
948
|
```ts
|
|
810
949
|
import {
|
|
811
950
|
KnuthMorrisPratt,
|
|
812
|
-
StringRollingHash,
|
|
813
951
|
RabinKarp,
|
|
952
|
+
Trie,
|
|
953
|
+
StringRollingHash,
|
|
814
954
|
RABIN_KARP_DEFAULT_MODS,
|
|
815
955
|
} from 'typescript-dsa-stl';
|
|
816
956
|
|
|
@@ -847,6 +987,16 @@ console.log(RabinKarp.findOccurrences('aaaa', 'aa')); // [0, 1, 2]
|
|
|
847
987
|
// Empty pattern: no matches
|
|
848
988
|
console.log(new RabinKarp('').search('text')); // []
|
|
849
989
|
|
|
990
|
+
// --- Trie: dictionary and prefix queries ---
|
|
991
|
+
const trie = new Trie();
|
|
992
|
+
trie.insert('apple');
|
|
993
|
+
trie.insert('app');
|
|
994
|
+
console.log(trie.search('app')); // true
|
|
995
|
+
console.log(trie.search('ap')); // false
|
|
996
|
+
console.log(trie.startsWith('ap')); // true
|
|
997
|
+
console.log(trie.delete('app')); // true
|
|
998
|
+
console.log(trie.search('app')); // false
|
|
999
|
+
|
|
850
1000
|
// --- String rolling hash: default base 131, mod 1_000_000_007 (both configurable) ---
|
|
851
1001
|
const rh = new StringRollingHash('hello');
|
|
852
1002
|
// Internally: prefix[] and pow[] so substring hashes are O(1)
|
|
@@ -21,6 +21,55 @@ export declare function breadthFirstSearch(n: number, adj: AdjacencyList<number>
|
|
|
21
21
|
* - Neighbors are explored in the order they appear in `adj[u]` (first neighbor in the list is visited first).
|
|
22
22
|
*/
|
|
23
23
|
export declare function depthFirstSearch(n: number, adj: AdjacencyList<number>, start: number): number[];
|
|
24
|
+
/**
|
|
25
|
+
* Result of a topological sort attempt on vertices `0..n-1`.
|
|
26
|
+
*
|
|
27
|
+
* **When sorting is impossible:** classical topological order exists only for a **directed acyclic graph (DAG)**.
|
|
28
|
+
* If the graph has any **directed cycle** (including a **self-loop**), both algorithms set `ok` to `false`.
|
|
29
|
+
* Treating an **undirected** edge as two opposite directed arcs creates a 2-cycle, so `ok` will be `false`
|
|
30
|
+
* unless there are no such pairs (e.g. only isolated vertices).
|
|
31
|
+
*
|
|
32
|
+
* **Input:** You must pass **`n` and `adj` together** — `n` is the number of vertices, and `adj[u]` lists **out-neighbors**
|
|
33
|
+
* of `u` for a **directed** graph. Missing `adj[u]` is treated as no outgoing edges. Neighbors outside `0..n-1` are **ignored**,
|
|
34
|
+
* so the result reflects that pruned graph, not raw adjacency data with invalid indices.
|
|
35
|
+
*/
|
|
36
|
+
export interface TopologicalSortResult {
|
|
37
|
+
/** A permutation of `0..n-1` with every edge `u → v` having `u` before `v` (only valid when `ok` is true). */
|
|
38
|
+
order: number[];
|
|
39
|
+
/** `true` iff a topological order exists for the directed graph on `0..n-1` after ignoring invalid neighbors. */
|
|
40
|
+
ok: boolean;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Topological ordering of a **directed** graph using an explicit stack (iterative DFS / finish times).
|
|
44
|
+
* Pushes a vertex after all its outgoing edges have been explored, then reverses that list.
|
|
45
|
+
*
|
|
46
|
+
* Complexity: O(n + m) time, O(n) extra space.
|
|
47
|
+
*
|
|
48
|
+
* **Inputs:** Same as other graph helpers: vertex count `n` and unweighted `adj` (outgoing edges only). This pair **is** the
|
|
49
|
+
* graph representation here; there is no separate graph object. Keep `n` consistent with how many vertices you number (`0..n-1`).
|
|
50
|
+
*
|
|
51
|
+
* **Not possible:** Returns `{ order: [], ok: false }` if a directed cycle is found (self-loop, longer cycle, or bidirectional
|
|
52
|
+
* undirected modeling). Returns `{ order, ok: true }` for any DAG, including disconnected ones.
|
|
53
|
+
*
|
|
54
|
+
* - Invalid neighbor indices are skipped (see {@link TopologicalSortResult}).
|
|
55
|
+
* - Parallel edges behave like multiple arcs; self-loops are cycles.
|
|
56
|
+
*/
|
|
57
|
+
export declare function topologicalSortStack(n: number, adj: AdjacencyList<number>): TopologicalSortResult;
|
|
58
|
+
/**
|
|
59
|
+
* Topological ordering via **Kahn's algorithm**: repeatedly remove vertices with indegree zero (BFS-style).
|
|
60
|
+
* Uses only indegrees derived from `adj`; outdegree is implicit in the lists.
|
|
61
|
+
*
|
|
62
|
+
* Complexity: O(n + m) time, O(n) extra space.
|
|
63
|
+
*
|
|
64
|
+
* **Inputs:** Requires `n` and `adj` together (directed out-edges per vertex), like {@link topologicalSortStack}.
|
|
65
|
+
*
|
|
66
|
+
* **Not possible:** `ok` is `false` when not all vertices are output — equivalently, when the graph on `0..n-1` (after ignoring
|
|
67
|
+
* invalid neighbors) contains a directed cycle. On failure, `order` lists some vertices in a valid partial order but must not
|
|
68
|
+
* be treated as a full topological sort.
|
|
69
|
+
*
|
|
70
|
+
* - When `ok` is `true`, `order` is one valid topological order; it may differ from the stack/DFS-based order.
|
|
71
|
+
*/
|
|
72
|
+
export declare function topologicalSortIndegree(n: number, adj: AdjacencyList<number>): TopologicalSortResult;
|
|
24
73
|
export interface WeightedUndirectedEdge {
|
|
25
74
|
u: number;
|
|
26
75
|
v: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../../src/algorithms/graph.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAIpF;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,EAC1B,KAAK,EAAE,MAAM,GACZ,MAAM,EAAE,CAmBV;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAC9B,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,EAC1B,KAAK,EAAE,MAAM,GACZ,MAAM,EAAE,CAiBV;AAED,MAAM,WAAW,sBAAsB;IACrC,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,GACzB,MAAM,EAAE,EAAE,CAQZ;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CACxB,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,qBAAqB,CAAC,MAAM,EAAE,MAAM,CAAC,EAC1C,OAAO,CAAC,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,GACjC;IAAE,KAAK,EAAE,sBAAsB,EAAE,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAgC1D;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CACtB,CAAC,EAAE,MAAM,EACT,GAAG,EA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AAC,GACzB,qBAAqB,CA0BvB;AAED,MAAM,WAAW,sBAAsB;IACrC,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,GACzB,MAAM,EAAE,EAAE,CAQZ;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CACxB,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,qBAAqB,CAAC,MAAM,EAAE,MAAM,CAAC,EAC1C,OAAO,CAAC,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,GACjC;IAAE,KAAK,EAAE,sBAAsB,EAAE,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAgC1D;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CACtB,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,qBAAqB,CAAC,MAAM,EAAE,MAAM,CAAC,EAC1C,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5B;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAmCpC;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GACb,MAAM,EAAE,CAgBV"}
|
package/dist/algorithms/graph.js
CHANGED
|
@@ -62,6 +62,101 @@ export function depthFirstSearch(n, adj, start) {
|
|
|
62
62
|
}
|
|
63
63
|
return order;
|
|
64
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Topological ordering of a **directed** graph using an explicit stack (iterative DFS / finish times).
|
|
67
|
+
* Pushes a vertex after all its outgoing edges have been explored, then reverses that list.
|
|
68
|
+
*
|
|
69
|
+
* Complexity: O(n + m) time, O(n) extra space.
|
|
70
|
+
*
|
|
71
|
+
* **Inputs:** Same as other graph helpers: vertex count `n` and unweighted `adj` (outgoing edges only). This pair **is** the
|
|
72
|
+
* graph representation here; there is no separate graph object. Keep `n` consistent with how many vertices you number (`0..n-1`).
|
|
73
|
+
*
|
|
74
|
+
* **Not possible:** Returns `{ order: [], ok: false }` if a directed cycle is found (self-loop, longer cycle, or bidirectional
|
|
75
|
+
* undirected modeling). Returns `{ order, ok: true }` for any DAG, including disconnected ones.
|
|
76
|
+
*
|
|
77
|
+
* - Invalid neighbor indices are skipped (see {@link TopologicalSortResult}).
|
|
78
|
+
* - Parallel edges behave like multiple arcs; self-loops are cycles.
|
|
79
|
+
*/
|
|
80
|
+
export function topologicalSortStack(n, adj) {
|
|
81
|
+
const state = new Uint8Array(n); // 0 = unvisited, 1 = on stack (visiting), 2 = done
|
|
82
|
+
const finish = [];
|
|
83
|
+
const stack = [];
|
|
84
|
+
for (let s = 0; s < n; s++) {
|
|
85
|
+
if (state[s] !== 0)
|
|
86
|
+
continue;
|
|
87
|
+
state[s] = 1;
|
|
88
|
+
stack.push({ u: s, i: 0 });
|
|
89
|
+
while (stack.length > 0) {
|
|
90
|
+
const top = stack[stack.length - 1];
|
|
91
|
+
const u = top.u;
|
|
92
|
+
const neighbors = adj[u] ?? [];
|
|
93
|
+
let pushedChild = false;
|
|
94
|
+
while (top.i < neighbors.length) {
|
|
95
|
+
const v = neighbors[top.i];
|
|
96
|
+
top.i++;
|
|
97
|
+
if (v < 0 || v >= n)
|
|
98
|
+
continue;
|
|
99
|
+
if (state[v] === 1)
|
|
100
|
+
return { order: [], ok: false };
|
|
101
|
+
if (state[v] === 0) {
|
|
102
|
+
state[v] = 1;
|
|
103
|
+
stack.push({ u: v, i: 0 });
|
|
104
|
+
pushedChild = true;
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!pushedChild) {
|
|
109
|
+
stack.pop();
|
|
110
|
+
state[u] = 2;
|
|
111
|
+
finish.push(u);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
finish.reverse();
|
|
116
|
+
return { order: finish, ok: true };
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Topological ordering via **Kahn's algorithm**: repeatedly remove vertices with indegree zero (BFS-style).
|
|
120
|
+
* Uses only indegrees derived from `adj`; outdegree is implicit in the lists.
|
|
121
|
+
*
|
|
122
|
+
* Complexity: O(n + m) time, O(n) extra space.
|
|
123
|
+
*
|
|
124
|
+
* **Inputs:** Requires `n` and `adj` together (directed out-edges per vertex), like {@link topologicalSortStack}.
|
|
125
|
+
*
|
|
126
|
+
* **Not possible:** `ok` is `false` when not all vertices are output — equivalently, when the graph on `0..n-1` (after ignoring
|
|
127
|
+
* invalid neighbors) contains a directed cycle. On failure, `order` lists some vertices in a valid partial order but must not
|
|
128
|
+
* be treated as a full topological sort.
|
|
129
|
+
*
|
|
130
|
+
* - When `ok` is `true`, `order` is one valid topological order; it may differ from the stack/DFS-based order.
|
|
131
|
+
*/
|
|
132
|
+
export function topologicalSortIndegree(n, adj) {
|
|
133
|
+
const indeg = new Uint32Array(n);
|
|
134
|
+
for (let u = 0; u < n; u++) {
|
|
135
|
+
for (const v of adj[u] ?? []) {
|
|
136
|
+
if (v >= 0 && v < n)
|
|
137
|
+
indeg[v]++;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const q = [];
|
|
141
|
+
for (let i = 0; i < n; i++) {
|
|
142
|
+
if (indeg[i] === 0)
|
|
143
|
+
q.push(i);
|
|
144
|
+
}
|
|
145
|
+
const order = [];
|
|
146
|
+
let qh = 0;
|
|
147
|
+
while (qh < q.length) {
|
|
148
|
+
const u = q[qh++];
|
|
149
|
+
order.push(u);
|
|
150
|
+
for (const v of adj[u] ?? []) {
|
|
151
|
+
if (v < 0 || v >= n)
|
|
152
|
+
continue;
|
|
153
|
+
indeg[v]--;
|
|
154
|
+
if (indeg[v] === 0)
|
|
155
|
+
q.push(v);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { order, ok: order.length === n };
|
|
159
|
+
}
|
|
65
160
|
/**
|
|
66
161
|
* Connected components in an (unweighted) graph using DSU.
|
|
67
162
|
* Complexity: O((n + m) * alpha(n)).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","sourceRoot":"","sources":["../../src/algorithms/graph.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,CAAS,EACT,GAA0B,EAC1B,KAAa;IAEb,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IACvC,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC/B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,CAAC,GAAa,EAAE,CAAC;IACvB,IAAI,EAAE,GAAG,CAAC,CAAC;IACX,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACd,OAAO,EAAE,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;QACrB,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAE,CAAC;QACnB,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,KAAK,MAAM,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YAC7B,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;gBAChC,IAAI,CAAC,CAAC,CAA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C;IAErC,MAAM,IAAI,GAAa,EAAE,CAAC;IAC1B,IAAI,CAAC,GAAG,MAAM,CAAC;IACf,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QACjD,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACb,IAAI,CAAC,KAAK,KAAK;YAAE,MAAM;QACvB,CAAC,GAAG,IAAI,CAAC,CAAC,CAAE,CAAC;QACb,IAAI,CAAC,KAAK,CAAC,CAAC;YAAE,OAAO,EAAE,CAAC;IAC1B,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,KAAK;QAAE,OAAO,EAAE,CAAC;IAC/C,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,IAAI,CAAC;AACd,CAAC"}
|
|
@@ -3,7 +3,8 @@ export { DisjointSetUnion } from './disjointSetUnion.js';
|
|
|
3
3
|
export { KnuthMorrisPratt } from './kmp.js';
|
|
4
4
|
export { StringRollingHash } from './stringHashing.js';
|
|
5
5
|
export { RabinKarp, RABIN_KARP_DEFAULT_MODS } from './rabinKarp.js';
|
|
6
|
+
export { Trie } from './trie.js';
|
|
6
7
|
export type { RabinKarpTripleMods } from './rabinKarp.js';
|
|
7
|
-
export type { WeightedUndirectedEdge } from './graph.js';
|
|
8
|
-
export { breadthFirstSearch, depthFirstSearch, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './graph.js';
|
|
8
|
+
export type { WeightedUndirectedEdge, TopologicalSortResult } from './graph.js';
|
|
9
|
+
export { breadthFirstSearch, depthFirstSearch, topologicalSortStack, topologicalSortIndegree, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './graph.js';
|
|
9
10
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/algorithms/index.ts"],"names":[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B,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,UAAU,GACX,MAAM,YAAY,CAAC"}
|
package/dist/algorithms/index.js
CHANGED
|
@@ -3,5 +3,6 @@ export { DisjointSetUnion } from './disjointSetUnion.js';
|
|
|
3
3
|
export { KnuthMorrisPratt } from './kmp.js';
|
|
4
4
|
export { StringRollingHash } from './stringHashing.js';
|
|
5
5
|
export { RabinKarp, RABIN_KARP_DEFAULT_MODS } from './rabinKarp.js';
|
|
6
|
-
export {
|
|
6
|
+
export { Trie } from './trie.js';
|
|
7
|
+
export { breadthFirstSearch, depthFirstSearch, topologicalSortStack, topologicalSortIndegree, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './graph.js';
|
|
7
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/algorithms/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,EACH,GAAG,EACH,SAAS,GACV,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/algorithms/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,EACH,GAAG,EACH,SAAS,GACV,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,UAAU,GACX,MAAM,YAAY,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trie (prefix tree) for UTF-16 strings.
|
|
3
|
+
* Supports insert/search/prefix checks and word removal.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Trie {
|
|
6
|
+
private readonly root;
|
|
7
|
+
constructor();
|
|
8
|
+
/** Insert a word into the trie. */
|
|
9
|
+
insert(word: string): void;
|
|
10
|
+
/** Returns true if the exact word exists in the trie. */
|
|
11
|
+
search(word: string): boolean;
|
|
12
|
+
/** Returns true if there is any inserted word with this prefix. */
|
|
13
|
+
startsWith(prefix: string): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Remove one exact word from the trie.
|
|
16
|
+
* Returns true when the word existed and was removed.
|
|
17
|
+
*/
|
|
18
|
+
delete(word: string): boolean;
|
|
19
|
+
/** Returns true when no words have been inserted. */
|
|
20
|
+
isEmpty(): boolean;
|
|
21
|
+
private findNode;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=trie.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trie.d.ts","sourceRoot":"","sources":["../../src/algorithms/trie.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,qBAAa,IAAI;IACf,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAW;;IAMhC,mCAAmC;IACnC,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAc1B,yDAAyD;IACzD,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAK7B,mEAAmE;IACnE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAInC;;;OAGG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAwB7B,qDAAqD;IACrD,OAAO,IAAI,OAAO;IAIlB,OAAO,CAAC,QAAQ;CASjB"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trie (prefix tree) for UTF-16 strings.
|
|
3
|
+
* Supports insert/search/prefix checks and word removal.
|
|
4
|
+
*/
|
|
5
|
+
class TrieNode {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.children = new Map();
|
|
8
|
+
this.isWord = false;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export class Trie {
|
|
12
|
+
constructor() {
|
|
13
|
+
this.root = new TrieNode();
|
|
14
|
+
}
|
|
15
|
+
/** Insert a word into the trie. */
|
|
16
|
+
insert(word) {
|
|
17
|
+
let node = this.root;
|
|
18
|
+
for (let i = 0; i < word.length; i++) {
|
|
19
|
+
const ch = word[i];
|
|
20
|
+
let next = node.children.get(ch);
|
|
21
|
+
if (!next) {
|
|
22
|
+
next = new TrieNode();
|
|
23
|
+
node.children.set(ch, next);
|
|
24
|
+
}
|
|
25
|
+
node = next;
|
|
26
|
+
}
|
|
27
|
+
node.isWord = true;
|
|
28
|
+
}
|
|
29
|
+
/** Returns true if the exact word exists in the trie. */
|
|
30
|
+
search(word) {
|
|
31
|
+
const node = this.findNode(word);
|
|
32
|
+
return node !== undefined && node.isWord;
|
|
33
|
+
}
|
|
34
|
+
/** Returns true if there is any inserted word with this prefix. */
|
|
35
|
+
startsWith(prefix) {
|
|
36
|
+
return this.findNode(prefix) !== undefined;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Remove one exact word from the trie.
|
|
40
|
+
* Returns true when the word existed and was removed.
|
|
41
|
+
*/
|
|
42
|
+
delete(word) {
|
|
43
|
+
const path = [];
|
|
44
|
+
let node = this.root;
|
|
45
|
+
for (let i = 0; i < word.length; i++) {
|
|
46
|
+
const ch = word[i];
|
|
47
|
+
const next = node.children.get(ch);
|
|
48
|
+
if (!next)
|
|
49
|
+
return false;
|
|
50
|
+
path.push({ parent: node, ch, node: next });
|
|
51
|
+
node = next;
|
|
52
|
+
}
|
|
53
|
+
if (!node.isWord)
|
|
54
|
+
return false;
|
|
55
|
+
node.isWord = false;
|
|
56
|
+
// Prune nodes that are no longer needed.
|
|
57
|
+
for (let i = path.length - 1; i >= 0; i--) {
|
|
58
|
+
const segment = path[i];
|
|
59
|
+
if (segment.node.isWord || segment.node.children.size > 0)
|
|
60
|
+
break;
|
|
61
|
+
segment.parent.children.delete(segment.ch);
|
|
62
|
+
}
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
/** Returns true when no words have been inserted. */
|
|
66
|
+
isEmpty() {
|
|
67
|
+
return this.root.children.size === 0;
|
|
68
|
+
}
|
|
69
|
+
findNode(path) {
|
|
70
|
+
let node = this.root;
|
|
71
|
+
for (let i = 0; i < path.length; i++) {
|
|
72
|
+
const next = node.children.get(path[i]);
|
|
73
|
+
if (!next)
|
|
74
|
+
return undefined;
|
|
75
|
+
node = next;
|
|
76
|
+
}
|
|
77
|
+
return node;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=trie.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trie.js","sourceRoot":"","sources":["../../src/algorithms/trie.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,QAAQ;IAAd;QACW,aAAQ,GAAG,IAAI,GAAG,EAAoB,CAAC;QAChD,WAAM,GAAG,KAAK,CAAC;IACjB,CAAC;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AAI,CAAC,IAAI;gBAAE,OAAO,SAAS,CAAC;YAC5B,IAAI,GAAG,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export { Vector, Stack, Queue, Deque, List, ListNode, PriorityQueue, OrderedMap, UnorderedMap, OrderedSet, UnorderedSet, OrderedMultiSet, OrderedMultiMap, addEdge, deleteEdge, createAdjacencyList, createWeightedAdjacencyList, GeneralSegmentTree, SegmentTree, SegmentTreeSum, SegmentTreeMin, SegmentTreeMax, LazySegmentTreeSum, } from './collections/index.js';
|
|
9
9
|
export type { WeightedEdge, AdjacencyList, WeightedAdjacencyList, GeneralSegmentTreeConfig, SegmentCombine, SegmentLeafBuild, SegmentMerge, } from './collections/index.js';
|
|
10
|
-
export { sort, find, findIndex, transform, filter, reduce, reverse, unique, binarySearch, lowerBound, upperBound, min, max, partition, DisjointSetUnion, KnuthMorrisPratt, StringRollingHash, RabinKarp, RABIN_KARP_DEFAULT_MODS, breadthFirstSearch, depthFirstSearch, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './algorithms/index.js';
|
|
11
|
-
export type { WeightedUndirectedEdge, RabinKarpTripleMods } from './algorithms/index.js';
|
|
10
|
+
export { sort, find, findIndex, transform, filter, reduce, reverse, unique, binarySearch, lowerBound, upperBound, min, max, partition, DisjointSetUnion, KnuthMorrisPratt, StringRollingHash, RabinKarp, Trie, RABIN_KARP_DEFAULT_MODS, breadthFirstSearch, depthFirstSearch, topologicalSortStack, topologicalSortIndegree, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './algorithms/index.js';
|
|
11
|
+
export type { WeightedUndirectedEdge, RabinKarpTripleMods, TopologicalSortResult, } from './algorithms/index.js';
|
|
12
12
|
export { clamp, range, noop, identity, swap } from './utils/index.js';
|
|
13
13
|
export type { Comparator, Predicate, UnaryFn, Reducer, IterableLike } from './types/index.js';
|
|
14
14
|
export { toArray } from './types/index.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,MAAM,EACN,KAAK,EACL,KAAK,EACL,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,UAAU,EACV,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,eAAe,EACf,eAAe,EACf,OAAO,EACP,UAAU,EACV,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,cAAc,EACd,cAAc,EACd,cAAc,EACd,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,YAAY,EACZ,aAAa,EACb,qBAAqB,EACrB,wBAAwB,EACxB,cAAc,EACd,gBAAgB,EAChB,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,EACH,GAAG,EACH,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,EACT,uBAAuB,EACvB,kBAAkB,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,UAAU,GACX,MAAM,uBAAuB,CAAC;AAC/B,YAAY,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,MAAM,EACN,KAAK,EACL,KAAK,EACL,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,UAAU,EACV,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,eAAe,EACf,eAAe,EACf,OAAO,EACP,UAAU,EACV,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,cAAc,EACd,cAAc,EACd,cAAc,EACd,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,YAAY,EACZ,aAAa,EACb,qBAAqB,EACrB,wBAAwB,EACxB,cAAc,EACd,gBAAgB,EAChB,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,EACH,GAAG,EACH,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,EACT,IAAI,EACJ,uBAAuB,EACvB,kBAAkB,EAClB,gBAAgB,EAChB,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,UAAU,GACX,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EACV,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACtE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC9F,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* import { Vector, Stack, Queue, List, sort, binarySearch, clamp } from 'typescript-dsa-stl';
|
|
7
7
|
*/
|
|
8
8
|
export { Vector, Stack, Queue, Deque, List, ListNode, PriorityQueue, OrderedMap, UnorderedMap, OrderedSet, UnorderedSet, OrderedMultiSet, OrderedMultiMap, addEdge, deleteEdge, createAdjacencyList, createWeightedAdjacencyList, GeneralSegmentTree, SegmentTree, SegmentTreeSum, SegmentTreeMin, SegmentTreeMax, LazySegmentTreeSum, } from './collections/index.js';
|
|
9
|
-
export { sort, find, findIndex, transform, filter, reduce, reverse, unique, binarySearch, lowerBound, upperBound, min, max, partition, DisjointSetUnion, KnuthMorrisPratt, StringRollingHash, RabinKarp, RABIN_KARP_DEFAULT_MODS, breadthFirstSearch, depthFirstSearch, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './algorithms/index.js';
|
|
9
|
+
export { sort, find, findIndex, transform, filter, reduce, reverse, unique, binarySearch, lowerBound, upperBound, min, max, partition, DisjointSetUnion, KnuthMorrisPratt, StringRollingHash, RabinKarp, Trie, RABIN_KARP_DEFAULT_MODS, breadthFirstSearch, depthFirstSearch, topologicalSortStack, topologicalSortIndegree, connectedComponents, dijkstra, reconstructPath, kruskalMST, } from './algorithms/index.js';
|
|
10
10
|
export { clamp, range, noop, identity, swap } from './utils/index.js';
|
|
11
11
|
export { toArray } from './types/index.js';
|
|
12
12
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,MAAM,EACN,KAAK,EACL,KAAK,EACL,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,UAAU,EACV,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,eAAe,EACf,eAAe,EACf,OAAO,EACP,UAAU,EACV,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,cAAc,EACd,cAAc,EACd,cAAc,EACd,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EACL,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,EACH,GAAG,EACH,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,EACT,uBAAuB,EACvB,kBAAkB,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,UAAU,GACX,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,MAAM,EACN,KAAK,EACL,KAAK,EACL,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,UAAU,EACV,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,eAAe,EACf,eAAe,EACf,OAAO,EACP,UAAU,EACV,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,cAAc,EACd,cAAc,EACd,cAAc,EACd,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EACL,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,UAAU,EACV,GAAG,EACH,GAAG,EACH,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,EACT,IAAI,EACJ,uBAAuB,EACvB,kBAAkB,EAClB,gBAAgB,EAChB,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,UAAU,GACX,MAAM,uBAAuB,CAAC;AAM/B,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAEtE,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typescript-dsa-stl",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.0",
|
|
4
4
|
"description": "STL-style data structures and algorithms for TypeScript: Vector, Stack, Queue, Deque (double-ended queue), List, PriorityQueue, Map, Set, sort, binarySearch, graph utilities. Use like C++ STL.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -54,6 +54,7 @@
|
|
|
54
54
|
"queue",
|
|
55
55
|
"deque",
|
|
56
56
|
"double-ended-queue",
|
|
57
|
+
"graph",
|
|
57
58
|
"list",
|
|
58
59
|
"priority-queue",
|
|
59
60
|
"map",
|