JavaScript Algorithms in TypeScript: Data Structures and Algorithms Explained, Typed and Tested
A collection of classic data structures and algorithms implemented in TypeScript, the typed way to study JavaScript algorithms. Each one comes with a plain-English explanation, its time and space complexity, and a test suite you can run in one command. It is for JavaScript and TypeScript developers preparing for coding interviews, students taking a data structures course, and anyone who wants to see how a heap, trie, LRU cache, Bloom filter, Dijkstra’s algorithm or a dynamic programming solution actually works in readable, strictly typed code.
There are zero dependencies. Tests use Node’s built-in node:test runner and node:assert/strict, and Node runs the .ts files directly through its built-in TypeScript type stripping. No npm install, no build step, no transpiler.
Last reviewed: December 2026
Table of contents
- Quick start
- How the repository is organized
- Data structures
- Algorithms
- Complexity cheat sheet
- Big-O in five minutes
- Built-ins vs hand-rolled: what JavaScript already gives you
- Best picks: which structure or algorithm to reach for
- Recognizing interview patterns
- Explanations
- Arrays vs linked structures
- Why heaps are stored in arrays
- How an LRU cache gets O(1) everything
- Picking a sorting algorithm
- Binary search without off-by-one bugs
- Choosing a graph algorithm
- How to approach a dynamic programming problem
- Segment tree or Fenwick tree?
- String search: KMP vs Rabin-Karp vs Z
- Bloom filters: trading certainty for memory
- Sliding windows and monotonic deques
- Backtracking: choose, explore, un-choose
- Usage examples
- TypeScript conventions used here
- node:test cheat sheet
- Interview study plan
- FAQ
- Where to go next
- Contributing
- License
- Credits
Quick start
Requirements: a Node.js release that runs TypeScript by type stripping without flags. According to the Node.js TypeScript docs, that is v22.18.0 or newer on the 22.x line, or v23.6.0 and later. Check with:
node --version
node -p "process.features.typescript" # prints "strip" when type stripping is on
| Node.js version | Can run this repo? |
|---|---|
| 22.18.0 and later 22.x | Yes, type stripping is on by default |
| 23.6.0 and later | Yes, on by default |
| 24.12.0+ / 25.2.0+ | Yes, and type stripping is marked stable |
| 22.6.0 to 22.17.x | Only with --experimental-strip-types |
| 22.5 and older | No |
Run every test:
git clone https://github.com/Ralpberry-Labs/javascript-algorithms-typescript.git
cd javascript-algorithms-typescript
npm test
npm test runs node --test "src/**/*.test.ts". You can also run a single file or filter by test name:
node --test src/data-structures/heap.test.ts
node --test --test-name-pattern="stable" "src/**/*.test.ts"
Try an algorithm without writing a file:
node -e 'import("./src/algorithms/dynamic-programming/edit-distance.ts").then(m => console.log(m.editDistance("kitten", "sitting")))'
Optional type checking (not needed to run the tests): the repo ships a strict tsconfig.json. With TypeScript 5.8 or newer (the release that added erasableSyntaxOnly) and @types/node available, npx tsc -p . checks everything without emitting files.
How the repository is organized
src/
utils/comparator.ts shared Compare<T> type
data-structures/ one file per structure + its .test.ts
algorithms/
sorting/ comparison and integer sorts
searching/ binary search family, quickselect
graphs/ traversal, shortest paths, MST, topo sort
dynamic-programming/ knapsack, LCS, LIS, edit distance, coins
strings/ KMP, Rabin-Karp, Z, palindromes
math/ gcd, sieve, fast power, factorization
patterns/ two pointers, sliding window
backtracking/ N-Queens, subsets, permutations
Every source file starts with a doc comment that explains the idea, when to use it, and its complexity. The test file next to it doubles as a usage example.
Data structures
| # | Structure | Source | Test | What it is good for |
|---|---|---|---|---|
| 1 | Singly linked list | linked-list.ts | test | O(1) insert/remove at the front, in-place reversal |
| 2 | Stack | stack.ts | test | LIFO, undo, bracket matching (isBalanced) |
| 3 | Queue (ring buffer) | queue.ts | test | FIFO without O(n) shift, BFS |
| 4 | Binary heap / priority queue | heap.ts | test | Always get the smallest (or largest) item fast |
| 5 | Trie (prefix tree) | trie.ts | test | Autocomplete, prefix queries |
| 6 | LRU cache | lru-cache.ts | test | Bounded cache with O(1) get/set and eviction |
| 7 | Union-find (disjoint set) | union-find.ts | test | Connectivity, Kruskal, grouping |
| 8 | Binary search tree | binary-search-tree.ts | test | Ordered set, in-order traversal, delete with successor |
| 9 | Graph (adjacency list) | graph.ts | test | Directed/undirected, weighted edges |
| 10 | Hash map (separate chaining) | hash-map.ts | test | How Map works inside: hashing, buckets, resizing |
| 11 | Segment tree | segment-tree.ts | test | Range sum/min/max with point updates |
| 12 | Fenwick tree (BIT) | fenwick-tree.ts | test | Prefix sums with point updates, tiny code |
| 13 | Bloom filter | bloom-filter.ts | test | “Definitely not seen” checks in very little memory |
Algorithms
Sorting
All comparison sorts take (values, compare?), return a new array, and never mutate the input. They share one test suite (sort-test-cases.ts) that also checks stability where the algorithm promises it.
| # | Algorithm | Source | Test |
|---|---|---|---|
| 14 | Bubble sort | bubble-sort.ts | test |
| 15 | Insertion sort | insertion-sort.ts | test |
| 16 | Selection sort | selection-sort.ts | test |
| 17 | Merge sort | merge-sort.ts | test |
| 18 | Quick sort (3-way, median of three) | quick-sort.ts | test |
| 19 | Heap sort | heap-sort.ts | test |
| 20 | Counting sort | counting-sort.ts | test |
| 21 | Radix sort (LSD) | radix-sort.ts | test |
Searching
| # | Algorithm | Source | Test |
|---|---|---|---|
| 22 | Binary search, lower/upper bound, search on the answer | binary-search.ts | test |
| 23 | Exponential (galloping) search | exponential-search.ts | test |
| 24 | Quickselect (k-th smallest, median) | quickselect.ts | test |
Graphs
All graph algorithms work on the generic Graph<V>, so vertices can be strings, numbers or object references.
| # | Algorithm | Source | Test |
|---|---|---|---|
| 25 | Breadth-first search + unweighted shortest path | breadth-first-search.ts | test |
| 26 | Depth-first search + connected components | depth-first-search.ts | test |
| 27 | Dijkstra’s shortest paths | dijkstra.ts | test |
| 28 | Bellman-Ford (negative edges, cycle detection) | bellman-ford.ts | test |
| 29 | Floyd-Warshall (all pairs, path rebuild) | floyd-warshall.ts | test |
| 30 | Topological sort (Kahn) | topological-sort.ts | test |
| 31 | Kruskal’s minimum spanning tree | kruskal.ts | test |
Dynamic programming
| # | Problem | Source | Test |
|---|---|---|---|
| 32 | 0/1 knapsack (with item reconstruction) | knapsack.ts | test |
| 33 | Longest common subsequence | longest-common-subsequence.ts | test |
| 34 | Longest increasing subsequence, O(n log n) | longest-increasing-subsequence.ts | test |
| 35 | Edit (Levenshtein) distance | edit-distance.ts | test |
| 36 | Coin change (fewest coins, number of ways) | coin-change.ts | test |
Strings
| # | Algorithm | Source | Test |
|---|---|---|---|
| 37 | Knuth-Morris-Pratt search + prefix function | knuth-morris-pratt.ts | test |
| 38 | Rabin-Karp rolling hash search | rabin-karp.ts | test |
| 39 | Z-algorithm | z-algorithm.ts | test |
| 40 | Longest palindromic substring, isPalindrome |
longest-palindromic-substring.ts | test |
Math and number theory
| # | Algorithm | Source | Test |
|---|---|---|---|
| 41 | GCD, LCM, extended Euclid, modular inverse | gcd-lcm.ts | test |
| 42 | Sieve of Eratosthenes | sieve-of-eratosthenes.ts | test |
| 43 | Fast exponentiation, modular power (BigInt) | fast-exponentiation.ts | test |
| 44 | Primality test, prime factorization | prime-factorization.ts | test |
Array and string patterns
| # | Technique | Source | Test |
|---|---|---|---|
| 45 | Two pointers: pair with sum, 3-sum without duplicates | two-pointers.ts | test |
| 46 | Sliding window: window maximum (monotonic deque), longest substring without repeats | sliding-window.ts | test |
Backtracking
| # | Problem | Source | Test |
|---|---|---|---|
| 47 | N-Queens (all solutions, board rendering) | n-queens.ts | test |
| 48 | Subsets and permutations | subsets-permutations.ts | test |
Complexity cheat sheet
n = number of elements, V/E = vertices/edges, m = pattern length, W = knapsack capacity, h = tree height, k = value range.
Data structure operations
| Structure | Access / search | Insert | Delete | Extra notes |
|---|---|---|---|---|
| Array (built-in) | O(1) by index, O(n) search | O(1) amortized at end, O(n) in middle | O(1) at end, O(n) in middle | Best cache locality |
| Linked list | O(n) | O(1) at head/tail | O(1) at head, O(n) by value | No resizing |
| Stack | O(1) top | O(1) amortized | O(1) | |
| Queue (ring buffer) | O(1) front | O(1) amortized | O(1) | |
| Binary heap | O(1) min | O(log n) | O(log n) pop | Build from n values: O(n) |
| Trie | O(L) | O(L) | O(L) | L = word length |
| LRU cache | O(1) get | O(1) set | O(1) | Map + doubly linked list |
| Union-find | O(α(n)) find | — | — | α(n) ≤ 4 in practice |
| BST (unbalanced) | O(h) | O(h) | O(h) | h = log n average, n worst |
| Hash map | O(1) average | O(1) average | O(1) average | O(n) if all keys collide |
| Segment tree | O(log n) range query | O(log n) point update | — | Build O(n), any associative op |
| Fenwick tree | O(log n) prefix sum | O(log n) point add | — | Build O(n), invertible ops only |
| Bloom filter | O(k) membership | O(k) | not supported | False positives possible, no false negatives |
Sorting
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Bubble sort | n | n² | n² | 1 | Yes |
| Insertion sort | n | n² | n² | 1 | Yes |
| Selection sort | n² | n² | n² | 1 | No |
| Merge sort | n log n | n log n | n log n | n | Yes |
| Quick sort | n log n | n log n | n² | log n | No |
| Heap sort | n log n | n log n | n log n | 1 | No |
| Counting sort | n + k | n + k | n + k | n + k | Yes |
| Radix sort (d digits, base b) | d(n + b) | d(n + b) | d(n + b) | n + b | Yes |
(Extra space excludes the copy each function makes so the input stays untouched.)
Searching, graphs, DP, strings, math, patterns
| Algorithm | Time | Space |
|---|---|---|
| Binary search / lower bound / upper bound | O(log n) | O(1) |
| Exponential search | O(log i), i = target position | O(1) |
| Quickselect | O(n) average, O(n²) worst | O(1) |
| BFS / DFS | O(V + E) | O(V) |
| Dijkstra (binary heap) | O((V + E) log V) | O(V + E) |
| Bellman-Ford | O(V · E) | O(V) |
| Floyd-Warshall | O(V³) | O(V²) |
| Topological sort (Kahn) | O(V + E) | O(V) |
| Kruskal | O(E log E) | O(V + E) |
| 0/1 knapsack | O(n · W) | O(n · W), or O(W) for value only |
| Longest common subsequence | O(m · n) | O(m · n) |
| Longest increasing subsequence | O(n log n) | O(n) |
| Edit distance | O(m · n) | O(n) |
| Coin change | O(amount · coins) | O(amount) |
| KMP | O(n + m) | O(m) |
| Rabin-Karp | O(n + m) expected | O(1) |
| Z-algorithm | O(n + m) | O(n + m) |
| Longest palindromic substring (expand) | O(n²) | O(1) |
| Euclid’s GCD | O(log min(a, b)) | O(1) |
| Sieve of Eratosthenes | O(n log log n) | O(n) |
| Fast exponentiation | O(log e) | O(1) |
| Trial-division factorization | O(√n) | O(log n) |
| Two pointers (pair sum) / 3-sum | O(n) / O(n²) | O(1) / O(1) beyond the sorted copy |
| Sliding window maximum | O(n) | O(k) |
| Longest substring without repeats | O(n) | O(alphabet) |
| N-Queens (all solutions) | O(n!) worst case, heavily pruned | O(n) |
| Subsets / permutations | O(n · 2ⁿ) / O(n · n!) | output size |
Big-O in five minutes
Big-O describes how the work grows as the input grows, ignoring constant factors. Rough numbers for a modern laptop running JavaScript, assuming around 10⁸ simple operations per second:
| Complexity | n = 1 000 | n = 100 000 | n = 10 000 000 | Typical source |
|---|---|---|---|---|
| O(1) | instant | instant | instant | hash lookup, array index |
| O(log n) | ~10 steps | ~17 steps | ~23 steps | binary search, heap push |
| O(n) | instant | ~1 ms | ~0.1 s | one pass over the data |
| O(n log n) | instant | ~2 ms | ~2 s | good sorting |
| O(n²) | ~10 ms | ~100 s | days | nested loops over the data |
| O(2ⁿ) | never finishes for n > 40 | trying every subset |
Practical reading of this table:
- If
ncan reach 10⁵ or more, an O(n²) solution is usually too slow. Look for sorting, hashing, two pointers, a heap or binary search. - Constant factors still matter at small sizes. Insertion sort beats merge sort on 10 elements, which is why real sort implementations switch to it for small runs.
- Average and worst case can be very different (quick sort, hash maps). Know which one a library promises.
- Amortized O(1) (array push, ring-buffer enqueue) means an occasional expensive resize is paid for by many cheap operations; the total over n operations is O(n).
Built-ins vs hand-rolled: what JavaScript already gives you
Before writing a data structure, check whether the language already has one. This table compares the JavaScript built-ins with the hand-rolled versions in this repository.
| Need | Built-in | Cost / caveat | Hand-rolled here | Use the hand-rolled one when |
|---|---|---|---|---|
| Stack | Array push / pop |
O(1) amortized | stack.ts | You want a named type and intent-revealing API |
| Queue | Array push / shift |
shift moves every element: O(n) per call in general |
queue.ts | The queue is large or long-lived (BFS over big graphs, job queues) |
| Priority queue / heap | none | — | heap.ts | Always: JavaScript has no standard heap |
| Hash map | Map |
O(1) average, iterates in insertion order, any key type | hash-map.ts | Only to learn how hashing works; use Map in real code |
| Hash set | Set |
O(1) average, insertion order | — | — |
| LRU cache | Map (delete + set to refresh) |
O(1), very short code | lru-cache.ts | Interviews and ports to other languages |
| Sorted map / ordered set | none | — | binary-search-tree.ts | You need in-order traversal or min/max with inserts |
| Sorting | Array.prototype.sort, toSorted |
Stable (required since ES2019); V8 uses TimSort | sorting/ | Learning, or integer keys where counting/radix sort wins |
| Binary search | none | — | binary-search.ts | Always: there is no built-in binary search on arrays |
| Substring search | indexOf, includes, matchAll |
Fast in practice | strings/ | You need all overlapping matches, guarantees, or the prefix/Z arrays |
| Big exact integers | BigInt |
Slower than numbers | fast-exponentiation.ts | Modular arithmetic above 2^53 |
| Grouping | Object.groupBy, Map.groupBy |
ES2024, check your target runtime | — | — |
| Bit array | Uint8Array / Uint32Array |
Compact, zero-initialized | bloom-filter.ts, sieve | — |
JavaScript gotchas that break algorithm code:
| Gotcha | Example | Fix |
|---|---|---|
| Default sort compares as strings | [10, 9, 1].sort() gives [1, 10, 9] |
Always pass a comparator: sort((a, b) => a - b) |
sort mutates in place |
sorting a function argument changes the caller’s array | Use toSorted or copy first (all sorts here copy) |
| Numbers are doubles | integers are exact only up to Number.MAX_SAFE_INTEGER (2^53 - 1) |
Use BigInt for bigger exact values |
(a + b) / 2 is fractional |
(3 + 4) / 2 is 3.5 |
(lo + hi) >> 1 or Math.floor |
| String length counts UTF-16 units | "😀".length is 2 |
Iterate with for...of or [...text] for code points |
| Deep recursion overflows | a recursive DFS on a 100 000-node path throws RangeError |
Use an explicit stack (depth-first-search.ts) |
Math.max(...hugeArray) |
spreading very large arrays can exceed engine argument limits | Use a loop or reduce |
| Object keys are strings | obj[1] and obj["1"] are the same key |
Use Map when keys are numbers or objects |
| Plain objects with integer-like keys reorder them | { b: 1, 2: 1, 1: 1 } iterates 1, 2, b |
Use Map when insertion order matters |
Best picks: which structure or algorithm to reach for
Short, opinionated answers for the most common situations, with the reason in one line.
| Situation | Best pick | Why |
|---|---|---|
| Sort anything in production | toSorted((a, b) => ...) |
Stable, heavily optimized, non-mutating |
| Sort a million small integers | Counting sort or radix sort | Linear time, no comparisons |
| Top-k largest of a stream | Min-heap of size k | O(n log k), constant memory |
| k-th smallest once | Quickselect | O(n) average, no full sort |
| Find in a sorted array | lowerBound | O(log n), also gives insertion point |
| Fewest hops between two nodes | BFS | Unweighted shortest path in O(V + E) |
| Cheapest route, weights ≥ 0 | Dijkstra | O((V + E) log V) |
| Negative weights | Bellman-Ford | Handles them and reports negative cycles |
| Distances between all pairs, small graph | Floyd-Warshall | Twelve lines of logic, O(V³) |
| Order tasks with dependencies | Topological sort | Detects cycles for free |
| “Are these connected?” with many merges | Union-find | Near O(1) per operation |
| Autocomplete | Trie | Cost depends on prefix length, not dictionary size |
| Bounded cache | LRU cache (or Map) |
O(1) eviction |
| “Seen this before?” over millions of keys | Bloom filter | About 1.2 bytes per key at 1% false positives |
| Range sums with updates | Fenwick tree | Shortest correct code |
| Range min/max with updates | Segment tree | Works for any associative operation |
| Fuzzy string match | Edit distance | Standard “did you mean” metric |
| Diff two sequences | LCS | The core of diff tools |
| Best value over contiguous windows | Sliding window | Turns O(n·k) into O(n) |
| Generate every arrangement | Backtracking | Simple, prunes early |
Recognizing interview patterns
Most interview questions are one of a handful of patterns in disguise. Learn to spot the signal in the wording.
| Signal in the problem | Pattern | Start from |
|---|---|---|
| “sorted array”, “pair that sums to” | Two pointers | two-pointers.ts |
| “contiguous subarray / substring”, “window of size k”, “longest without repeating” | Sliding window | sliding-window.ts |
| “k largest / smallest / most frequent”, “merge k sorted lists” | Heap | heap.ts |
| “minimum that satisfies”, “maximum such that”, monotone yes/no check | Binary search on the answer | firstTrue |
| “shortest path”, “fewest moves”, grid with walls | BFS | breadth-first-search.ts |
| “number of islands”, “connected groups”, “is there a path” | DFS / union-find | depth-first-search.ts, union-find.ts |
| “prerequisites”, “build order”, “can all courses be finished” | Topological sort | topological-sort.ts |
| “number of ways”, “minimum cost”, “is it possible” with overlapping choices | Dynamic programming | dynamic-programming/ |
| “all combinations / permutations / placements” | Backtracking | backtracking/ |
| “valid parentheses”, “next greater element”, “undo” | Stack | stack.ts |
| “prefix”, “starts with”, “word dictionary” | Trie | trie.ts |
| “range sum query” with updates | Fenwick / segment tree | fenwick-tree.ts |
| “least recently used”, “cache with capacity” | Hash map + linked list | lru-cache.ts |
Explanations
Arrays vs linked structures
An array keeps elements next to each other in memory. That gives O(1) indexing and excellent CPU cache behaviour, but inserting in the middle shifts everything after it. A linked list scatters nodes around memory and connects them with pointers, so inserting next to a node you already hold is O(1), but reaching the 500th element means following 500 pointers.
In JavaScript, arrays are so well optimized that they win most real benchmarks. Linked structures earn their place when you need stable references to elements while the collection changes (the LRU cache keeps direct pointers to its nodes) or when you are building another structure out of them (hash-map buckets, adjacency lists).
The queue shows a third option: a ring buffer, an array that wraps around, so both ends are O(1) without any pointers.
Why heaps are stored in arrays
A binary heap is a complete binary tree: every level is full except possibly the last, which fills left to right. Complete trees have no gaps, so they map perfectly onto an array:
index: 0 1 2 3 4 5
value: 1 3 2 7 4 9
tree: 1
/ \
3 2
/ \ /
7 4 9
children of i: 2i + 1 and 2i + 2 parent of i: (i - 1) >> 1
No node objects, no pointers, and the tree height is always ⌊log₂ n⌋, so push and pop are O(log n). Building a heap from n values by sifting down from the middle (Floyd’s method, used in the BinaryHeap constructor) is O(n), not O(n log n), because most nodes are near the bottom and barely move.
How an LRU cache gets O(1) everything
You need two things at once: find a key quickly (a hash map) and know which key was used least recently (an ordering). A doubly linked list gives the ordering, and because each map entry points straight at its list node, moving a node to the front or unlinking the tail are O(1) pointer swaps.
map: "a" ──┐ "b" ──┐ "c" ──┐
▼ ▼ ▼
HEAD ⇄ [ c ] ⇄ [ a ] ⇄ [ b ] ⇄ TAIL
most recent least recent → evicted next
The sentinel HEAD and TAIL nodes mean the list is never truly empty, so pushFront and unlink have no special cases. In JavaScript specifically, a Map remembers insertion order, so map.delete(key); map.set(key, value) moves a key to the end and map.keys().next() finds the oldest. That shortcut is fine for production code; the explicit list in lru-cache.ts is what interviewers and other languages expect.
Picking a sorting algorithm
In real TypeScript code, use Array.prototype.sort or toSorted with a comparator. Modern engines use TimSort-style stable sorts. Learning the classic algorithms still pays off because their ideas show up everywhere:
| Situation | Good choice | Why |
|---|---|---|
| Tiny or nearly sorted array | Insertion sort | Linear on sorted input, tiny constant |
| Need guaranteed n log n and stability | Merge sort | Same speed on every input, keeps ties in order |
| General in-memory sorting, speed matters | Quick sort | Fast in practice, in place |
| Memory is tight and worst case matters | Heap sort | n log n worst case, O(1) extra space |
| Integers in a small range | Counting sort | Linear, no comparisons |
| Many fixed-width integers or strings | Radix sort | Linear in n for a fixed number of digits |
| Writes are expensive (flash memory) | Selection sort | At most n - 1 swaps |
Stability means equal elements keep their original order. It matters when you sort by one key after another: sort by name, then stable-sort by age, and people of the same age stay alphabetical.
The quick sort here uses two upgrades worth knowing. Median-of-three pivot selection stops already-sorted input from triggering the O(n²) case. Three-way partitioning groups all values equal to the pivot in the middle, so an array of a million copies of the same number sorts in linear time instead of quadratic.
Binary search without off-by-one bugs
Most binary search bugs come from mixing interval conventions. This repo uses one rule everywhere: search the half-open range [lo, hi), and keep the invariant that the answer is in [lo, hi].
let lo = 0, hi = a.length; // answer is somewhere in [0, n]
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (a[mid] < target) lo = mid + 1; // answer is right of mid
else hi = mid; // mid could be the answer
}
return lo; // first index with a[i] >= target
With lowerBound and upperBound you can answer most questions without writing a new loop:
| Question | Expression |
|---|---|
Is x present? |
lowerBound(a, x) < a.length && a[lowerBound(a, x)] === x |
How many copies of x? |
upperBound(a, x) - lowerBound(a, x) |
Where should x be inserted to keep order? |
lowerBound(a, x) (before duplicates) or upperBound(a, x) (after) |
Largest element < x |
index lowerBound(a, x) - 1 |
Smallest element > x |
index upperBound(a, x) |
The same pattern works on numbers instead of arrays. firstTrue(lo, hi, predicate) finds the first integer where a monotone condition flips from false to true. That solves “minimum ship capacity to deliver in D days”, “smallest divisor such that the sum is under a threshold” and many similar problems: guess an answer, check it in O(n), and binary-search the guess.
Choosing a graph algorithm
| Goal | Use | Notes |
|---|---|---|
| Visit everything reachable | BFS or DFS | Either works; DFS uses less memory on wide graphs |
| Fewest edges between two vertices | BFS | Weights must all be equal |
| Cheapest path, non-negative weights | Dijkstra | The default for maps and routing |
| Cheapest path, some negative weights | Bellman-Ford | Also reports negative cycles |
| Cheapest paths between every pair | Floyd-Warshall | O(V³); fine up to a few hundred vertices |
| Order tasks with dependencies | Topological sort | Fails (returns null) if there is a cycle |
| Connect everything as cheaply as possible | Kruskal (or Prim) | Undirected graphs only |
| Are two vertices in the same group? (with many merges) | Union-find | Faster than re-running BFS each time |
| Group vertices into islands | DFS / BFS components, or union-find |
Common pitfalls the code avoids:
- BFS: mark a vertex visited when you enqueue it, not when you dequeue it, or it can be enqueued many times.
- DFS: recursion depth equals path length; a 100 000-vertex chain overflows the JavaScript call stack. The iterative version uses an explicit stack and is tested on exactly that.
- Dijkstra: a vertex can appear in the heap several times with different distances. Skip entries whose distance is larger than the best known one (“lazy deletion”) instead of implementing decrease-key.
- Bellman-Ford: with undirected graphs, a single negative edge is already a negative cycle (walk it back and forth).
How to approach a dynamic programming problem
Dynamic programming is recursion plus remembering answers to subproblems. It works when the problem has optimal substructure (the best answer is built from best answers to smaller pieces) and overlapping subproblems (the same pieces are needed again and again).
A five-step recipe that works for every DP file in this repo:
- Define the state in words. “best[i][w] = the highest value using only the first i items with capacity w.”
- Write the transition. Look at the last decision: take item i or skip it.
best[i][w] = max(best[i-1][w], value[i] + best[i-1][w - weight[i]]). - Set the base cases. Zero items or zero capacity is worth 0.
- Choose an evaluation order so every state you read is already computed (row by row, increasing w).
- Optimize memory if each row only reads the previous one. Knapsack and edit distance drop to a single row or two rows.
Top-down (recursion with a cache) and bottom-up (filling a table) give the same complexity. Top-down is easier to derive; bottom-up avoids recursion limits and makes memory tricks possible.
Spotting DP problems: the question asks for a minimum, maximum, count of ways, or “is it possible”, and a brute force would try exponentially many combinations of choices.
| File | State | Transition |
|---|---|---|
| knapsack | best[i][w] | skip item or take it |
| LCS | L[i][j] over prefixes | characters match → diagonal + 1, else max of dropping one |
| LIS | tails[k] = smallest tail of an increasing run of length k + 1 | binary search for where the value fits |
| edit distance | D[i][j] over prefixes | min of insert, delete, substitute |
| coin change | best[x] for each amount | 1 + best[x - coin] |
Segment tree or Fenwick tree?
Both answer range queries on an array that changes.
- A Fenwick tree is about 15 lines and very fast, but it only handles operations you can undo, such as sums and XOR, because a range sum is computed as
prefix(r) - prefix(l). - A segment tree handles any associative operation (min, max, gcd, even string concatenation, since the implementation here keeps left and right results separate). It needs twice the memory and a bit more code. With lazy propagation it also supports range updates.
If you only need prefix sums with updates, use Fenwick. If you need range minimum or maximum, use a segment tree. If the array never changes, a plain prefix-sum array (or a sparse table for min/max) is simpler than both.
String search: KMP vs Rabin-Karp vs Z
For everyday code, text.indexOf(pattern) and String.prototype.includes are the right choice. These three algorithms matter when you need guaranteed linear time, many patterns, or the helper arrays themselves.
| Algorithm | Guarantee | Best when |
|---|---|---|
| KMP | O(n + m) worst case | Streaming text, never re-reading input; the prefix function solves periodicity problems too |
| Rabin-Karp | O(n + m) expected | Searching for many patterns of the same length, finding duplicate chunks |
| Z-algorithm | O(n + m) worst case | When “longest prefix match at each position” is itself useful |
The prefix function and Z-array carry the same information in different shapes, and both appear in competitive programming far beyond plain search (counting distinct substrings, finding the shortest period of a string, string compression).
Bloom filters: trading certainty for memory
A Bloom filter answers “have I seen this key?” with two possible replies: definitely not, or probably yes. It never forgets a key it has seen (no false negatives), but it sometimes claims to have seen a key it has not (a false positive). In exchange, it uses a few bits per key no matter how long the keys are.
| Expected keys (n) | Target false-positive rate (p) | Bits (m) | Hash functions (k) | Memory |
|---|---|---|---|---|
| 1 000 | 1% | 9 586 | 7 | about 1.2 KB |
| 1 000 000 | 1% | about 9.6 million | 7 | about 1.2 MB |
| 1 000 000 | 0.1% | about 14.4 million | 10 | about 1.8 MB |
Those numbers come from m = -n·ln(p) / (ln 2)² and k = (m/n)·ln 2, the same formulas BloomFilter.forCapacity uses. The test suite checks the measured false-positive rate on 20 000 unseen keys.
When it is the right tool: a cheap check in front of an expensive lookup (a disk read, a network call), where an occasional unnecessary lookup is fine but a missed one is not. When it is not: when you need to delete keys (a plain Bloom filter cannot), or when you need an exact answer.
Sliding windows and monotonic deques
A sliding window keeps two indices, left and right, and a running summary of what lies between them. Because each index only moves forward, every element is added once and removed once, so the whole scan is O(n).
The window maximum is the classic hard case: when the largest value leaves the window, what is the new maximum? The trick is a monotonic deque of indices whose values decrease from front to back:
values: 1 3 -1 -3 5 3 6 7 window k = 3
i=2 deque values [3, -1] max 3
i=3 deque values [3, -1, -3] max 3
i=4 5 arrives: pop -3, -1, 3 deque [5] max 5
i=5 deque [5, 3] max 5
i=6 6 arrives: pop 3, 5 deque [6] max 6
i=7 7 arrives: pop 6 deque [7] max 7
A value that is smaller than a newer value can never be a window maximum again, so throwing it away is safe. The front leaves when its index falls out of the window. The JavaScript version keeps a head index instead of calling shift, so removing from the front stays O(1).
Backtracking: choose, explore, un-choose
Backtracking is depth-first search over decisions. Every solver in backtracking/ has the same three lines at its core:
path.push(choice); // choose
explore(next); // explore everything that follows from this choice
path.pop(); // un-choose, so the next choice starts clean
What makes it fast enough is pruning: reject a partial solution the moment it breaks a rule. N-Queens keeps sets of used columns and diagonals so “is this square attacked?” is O(1), which cuts the 8-queens search from billions of raw placements to a few thousand tried squares and the 92 solutions the tests check for.
| Problem | Results | Practical limit |
|---|---|---|
| Subsets of n items | 2ⁿ | n around 20 (about a million subsets) |
| Permutations of n items | n! | n around 10 (3.6 million permutations) |
| N-Queens solutions | 92 for n = 8, 724 for n = 10 | n in the low teens for all solutions |
Usage examples
All modules are plain ES modules, so you can import them from any Node 22.18+ script with the .ts extension.
import { BinaryHeap } from "./src/data-structures/heap.ts";
import { reverseCompare } from "./src/utils/comparator.ts";
// Top 3 scores with a min-heap of size 3
const scores = [42, 17, 99, 63, 8, 77];
const heap = new BinaryHeap<number>();
for (const s of scores) {
heap.push(s);
if (heap.size > 3) heap.pop();
}
console.log(heap.drain().reverse()); // [99, 77, 63]
// Max-heap
const max = new BinaryHeap(reverseCompare<number>(), scores);
console.log(max.peek()); // 99
import { Graph } from "./src/data-structures/graph.ts";
import { dijkstra, pathTo } from "./src/algorithms/graphs/dijkstra.ts";
const city = Graph.fromEdges<string>([
["home", "cafe", 4],
["home", "park", 2],
["park", "cafe", 1],
["cafe", "office", 5],
]);
const result = dijkstra(city, "home");
console.log(result.distances.get("office")); // 8
console.log(pathTo(result, "home", "office")); // ["home", "park", "cafe", "office"]
import { Trie } from "./src/data-structures/trie.ts";
const words = new Trie(["type", "typed", "typescript", "typo", "test"]);
console.log(words.withPrefix("typ")); // ["type", "typed", "typescript", "typo"]
console.log(words.withPrefix("typ", 2)); // ["type", "typed"]
import { LRUCache } from "./src/data-structures/lru-cache.ts";
const cache = new LRUCache<string, Response>(100);
cache.set("/home", new Response("hi"));
const evicted = cache.set("/about", new Response("about")); // undefined until full
import { editDistance } from "./src/algorithms/dynamic-programming/edit-distance.ts";
// "Did you mean...?"
const commands = ["install", "uninstall", "init", "test", "publish"];
const typo = "instal";
const suggestion = commands.reduce((best, c) =>
editDistance(typo, c) < editDistance(typo, best) ? c : best,
);
console.log(suggestion); // "install"
import { topologicalSort } from "./src/algorithms/graphs/topological-sort.ts";
import { Graph } from "./src/data-structures/graph.ts";
const deps = Graph.fromEdges<string>(
[["types", "core"], ["core", "cli"], ["core", "web"]],
{ directed: true },
);
console.log(topologicalSort(deps)); // ["types", "core", "cli", "web"]
import { BloomFilter } from "./src/data-structures/bloom-filter.ts";
// Skip a slow database lookup for usernames that were never registered
const registered = BloomFilter.forCapacity(1_000_000, 0.01);
registered.add("ada").add("grace");
console.log(registered.mightContain("ada")); // true
console.log(registered.mightContain("nobody")); // false (definitely not registered)
import { maxSlidingWindow, longestUniqueSubstring } from "./src/algorithms/patterns/sliding-window.ts";
// Highest temperature in every 3-day window
console.log(maxSlidingWindow([18, 21, 19, 25, 24, 20, 22], 3)); // [21, 25, 25, 25, 24]
console.log(longestUniqueSubstring("pwwkew")); // "wke"
import { threeSum } from "./src/algorithms/patterns/two-pointers.ts";
console.log(threeSum([-1, 0, 1, 2, -1, -4])); // [[-1, -1, 2], [-1, 0, 1]]
import { Graph } from "./src/data-structures/graph.ts";
import { floydWarshall } from "./src/algorithms/graphs/floyd-warshall.ts";
const flights = Graph.fromEdges<string>(
[["NYC", "LON", 7], ["LON", "DEL", 9], ["NYC", "DEL", 18]],
{ directed: true },
);
const all = floydWarshall(flights);
console.log(all.distance("NYC", "DEL")); // 16
console.log(all.path("NYC", "DEL")); // ["NYC", "LON", "DEL"]
import { solveNQueens, renderBoard } from "./src/algorithms/backtracking/n-queens.ts";
console.log(solveNQueens(8).length); // 92
console.log(renderBoard(solveNQueens(4)[0]).join("\n"));
// .Q..
// ...Q
// Q...
// ..Q.
TypeScript conventions used here
The code is written so Node can run it with type stripping alone: Node removes the type annotations and executes what is left, without a compiler. That imposes a few rules, enforced by erasableSyntaxOnly in tsconfig.json:
- Only erasable syntax. No
enum(use a union of string literals or anas constobject), nonamespace, and no constructor parameter properties (constructor(private x: number)). Write the field and assign it in the constructor instead. - Imports include the
.tsextension (import { Queue } from "./queue.ts"), enabled byallowImportingTsExtensions. Node resolves files exactly as written. - Type-only imports are marked with
import typeor an inlinetypemodifier, enforced byverbatimModuleSyntax, so the stripped JavaScript never imports something that does not exist at runtime. strictis on. Array reads that the code has already bounds-checked useas Tto keep the algorithm readable rather than adding runtime checks that can never fail.- Generics with comparators. Anything ordered takes a
Compare<T>(same contract asArray.prototype.sort), so the same heap or BST works for numbers, strings or objects sorted by any key. - No mutation of inputs. Sorting and selection functions copy first, so you can call them on frozen or shared arrays.
How common TypeScript features translate into erasable syntax:
| Instead of | Write | Why |
|---|---|---|
enum Color { Red, Green } |
const Color = { Red: "red", Green: "green" } as const; plus type Color = (typeof Color)[keyof typeof Color]; |
Enums generate runtime code that type stripping cannot produce |
constructor(private size: number) {} |
private size: number; then this.size = size; in the constructor |
Parameter properties also generate code |
namespace Geometry { export const pi = 3.14 } |
A module file: export const pi = 3.14; |
Namespaces with values are not erasable |
import fs = require("fs") |
import fs from "node:fs"; |
import = aliases are not erasable |
import { Graph } from "./graph" |
import type { Graph } from "./graph.ts" (type only) or import { Graph } from "./graph.ts" |
Node needs the real file extension; type-only imports must say so |
If you break one of these rules, Node stops with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX, and tsc with erasableSyntaxOnly reports it before you even run the code.
node:test cheat sheet
Everything below is built into Node, so this repository needs no test framework. Flags are as documented in the Node.js test runner docs.
| Task | Command or code |
|---|---|
| Run all tests here | npm test (same as node --test "src/**/*.test.ts"; quote the glob so Node expands it, not the shell) |
| Run one file | node --test src/data-structures/trie.test.ts |
| Run tests whose name matches | node --test --test-name-pattern="stable" "src/**/*.test.ts" |
| Skip tests whose name matches | node --test --test-skip-pattern="random" "src/**/*.test.ts" |
| Re-run on save | node --test --watch "src/**/*.test.ts" (marked experimental) |
| Coverage report | node --test --experimental-test-coverage "src/**/*.test.ts" |
| Default discovery | With no arguments, node --test also finds *.test.ts files when type stripping is on |
| Deep equality | assert.deepEqual(actual, expected) from node:assert/strict |
| Expect an error | assert.throws(() => fn(), RangeError) |
| Spy on a function | const spy = mock.fn(fn); spy.mock.callCount() |
| Fake timers | mock.timers.enable({ apis: ["setTimeout"] }); mock.timers.tick(1000) |
| Snapshot | t.assert.snapshot(value), update with --test-update-snapshots |
A minimal test file looks like this:
import { test } from "node:test";
import assert from "node:assert/strict";
import { gcd } from "./gcd-lcm.ts";
test("gcd of coprime numbers is 1", () => {
assert.equal(gcd(17, 5), 1);
});
Interview study plan
A suggested order if you are using this repo to prepare for coding interviews. Read the source, close it, re-implement from memory, then run the test file against your version.
| Week | Topics | Files |
|---|---|---|
| 1 | Arrays, stacks, queues, linked lists | stack, queue, linked-list (practice reverse until it is automatic) |
| 2 | Hashing, caches, two pointers, sliding window | hash-map, lru-cache, two-pointers, sliding-window |
| 3 | Sorting and binary search | merge-sort, quick-sort, binary-search (all three bounds), quickselect |
| 4 | Heaps and trees | heap, binary-search-tree, trie |
| 5 | Graph traversal | graph, BFS, DFS, topological-sort, union-find |
| 6 | Weighted graphs | dijkstra, bellman-ford, floyd-warshall, kruskal |
| 7 | Dynamic programming and backtracking | coin-change, knapsack, LCS, edit-distance, LIS, n-queens, subsets-permutations |
| 8 | Strings, math, range queries, probabilistic | KMP, Z, sieve, gcd, fast-exponentiation, segment-tree, fenwick-tree, bloom-filter |
Habits that help in the interview itself:
- Restate the problem and ask about input sizes; the size tells you the complexity you need (see Big-O in five minutes).
- Say the brute force and its complexity first, then improve it.
- Name the bottleneck and the tool that removes it: “the repeated minimum lookup becomes a heap”, “the nested loop over pairs becomes two pointers”.
- Test aloud with an empty input, one element and duplicates, exactly as the test files here do.
- State the final time and space complexity without being asked.
FAQ
What sorting algorithm does JavaScript’s Array.prototype.sort use?
The specification only requires the sort to be stable (since ES2019); the algorithm is up to the engine. V8, the engine in Chrome and Node.js, switched to TimSort in V8 7.0, as described on the V8 blog. TimSort is a merge sort that finds already-sorted runs and uses insertion sort for short ones; both building blocks are in sorting/.
Why does [10, 9, 1].sort() return [1, 10, 9]?
Without a comparator, sort converts elements to strings and compares them as text, and "10" comes before "9". Always pass (a, b) => a - b for numbers.
Is there a built-in priority queue or heap in JavaScript? No. Use a binary heap like heap.ts; it is about 70 lines and gives O(log n) push and pop.
How do I implement an efficient queue in JavaScript?
array.shift() has to move the remaining elements, so a queue built on push/shift becomes slow for large queues. Use a ring buffer (queue.ts) or keep a head index and never call shift (as sliding-window.ts does for its deque).
Should I use Map or a plain object as a hash map?
Use Map for algorithm code: keys can be any type, iteration follows insertion order, size is O(1), and there are no inherited keys like constructor to trip over.
Is a JavaScript Map ordered?
Yes, Map and Set iterate in insertion order. That is what makes the five-line Map version of an LRU cache work.
How do I run TypeScript in Node.js without ts-node or tsx?
On Node 22.18+ or 23.6+, run node file.ts directly. Node strips the type annotations and runs the rest. The rules are on the Node.js TypeScript page: use only erasable syntax, write .ts extensions in imports, and mark type-only imports with import type.
Why do I get ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX?
The file uses TypeScript syntax that needs code generation, such as an enum, a namespace with values or a constructor parameter property. See the translation table under TypeScript conventions used here.
What does erasableSyntaxOnly do?
It is a TypeScript compiler option, added in TypeScript 5.8, that reports an error for exactly the constructs Node cannot strip. Turning it on in tsconfig.json catches problems in the editor instead of at runtime.
Does node --test find .ts test files automatically?
Yes. With type stripping on, the default discovery patterns include *.test.ts and similar names. This repo still passes an explicit glob so only src/ is searched.
Why not use Jest or Vitest?
The goal is zero setup. Node’s built-in test runner covers everything these tests need (test, assert.deepEqual, assert.throws, name filters, watch mode, coverage, mocks).
Do I need TypeScript installed? No. Node strips the types itself. TypeScript is only needed for the optional type check.
How deep can recursion go in JavaScript? It depends on the engine and the size of each stack frame, typically thousands to tens of thousands of calls. Graph code that can see long paths should use an explicit stack, as depth-first-search.ts does (and tests with a 100 000-vertex path).
Why does the BST not balance itself?
To keep the core idea readable. The test sorted input degrades to a tall tree demonstrates exactly why balanced trees (AVL, red-black) exist.
Why BigInt in modPow but not in power?
power mirrors Math.pow for ordinary numbers. Modular arithmetic multiplies two values just under the modulus; for moduli above about 2²⁶ that product can exceed 2⁵³ and silently lose precision in a double, so BigInt is the safe choice.
Can I use these in production?
They are correct and tested, but written for clarity first. Prefer built-ins (Map, Set, toSorted) where they exist. Copying a single file that has no built-in equivalent (heap, union-find, Fenwick tree, Bloom filter) into a project is reasonable; each depends at most on the shared comparator or the hash function in hash-map.ts.
How is this different from a JavaScript-only algorithms collection?
Every structure is generic and strictly typed (BinaryHeap<T>, Graph<V>, LRUCache<K, V>), comparators are typed, and the code runs directly in Node with no build step. Types make the invariants explicit: a Compare<T> cannot accidentally receive a string comparator for numbers.
Where to go next
Every link below was checked in December 2026.
Official references
- Node.js: Modules: TypeScript: type stripping rules, supported syntax, version history.
- Node.js: Test runner and Assert: the APIs every test here uses.
- TypeScript Handbook: Generics and Classes.
- TSConfig reference: erasableSyntaxOnly and the TypeScript 5.8 announcement that introduced it.
- MDN: Array.prototype.sort, Array.prototype.toSorted, Map, Object.groupBy.
- V8 blog: Getting things sorted in V8: how and why V8 moved
Array.prototype.sortto TimSort. - ECMAScript language specification for the exact rules behind sorting,
Mapordering and numbers.
Free courses and books
- MIT OpenCourseWare 6.006 Introduction to Algorithms (Spring 2020): lectures, notes and problem sets.
- Algorithms, 4th edition booksite (Princeton): code and explanations for most of the structures here.
- Algorithms by Jeff Erickson: a free textbook with excellent chapters on recursion, backtracking and dynamic programming.
- Open Data Structures: a free, open-licensed data structures textbook.
Visualizers
- VisuAlgo: step-by-step animations of sorting, heaps, graphs, segment and Fenwick trees.
- Data Structure Visualizations (University of San Francisco): interactive trees, heaps, hashing and graph algorithms.
Practice and deeper reference
- LeetCode: problem sets to practice each pattern in the interview patterns table.
- NeetCode roadmap: problems grouped by pattern in a suggested order.
- Algorithms for Competitive Programming (cp-algorithms.com): rigorous articles on strings (prefix function, Z-function), number theory and graphs.
- Big-O Cheat Sheet: a one-page summary to compare against the tables above.
Contributing
Pull requests are welcome. To add an algorithm:
- Put the source in the matching folder, kebab-case file name, with a doc comment covering the idea, typical uses and time/space complexity.
- Add a
.test.tsnext to it with edge cases (empty input, single element, duplicates) and at least one comparison against a brute-force or built-in result. - Stick to erasable TypeScript syntax and
.tsimport extensions sonpm testkeeps working with no build step. - Add a row to the matching table in this README and to the complexity cheat sheet.
Please keep entries accurate: corrections to explanations, complexity claims or links are some of the most valuable contributions.
License
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.