Reservoir Sampling:One Pass When You Do Not Know n Up Front
Keep the first k items, then for each later index i (1-based), replace a slot with probability k/i — a uniform sample of k from a stream of unknown length.
Read More51 post(s)
Keep the first k items, then for each later index i (1-based), replace a slot with probability k/i — a uniform sample of k from a stream of unknown length.
Read MoreSquare the base and consume the exponent bit by bit — O(log exp) multiplies instead of a loop of exp products, for integers or modular pow.
Read MoreFor i from n-1 down to 1, swap a[i] with a uniform index in 0..i — every permutation equally likely, which is what Collections.shuffle already runs.
Read MoreReplace repeated subtraction with remainder, then back-substitute for Bézout coefficients — gcd, lcm, and a modular inverse when gcd is 1.
Read Mored × w counters and the min over hashes: over-estimate frequencies on purpose when a HashMap of every key will not fit.
Read MoreBuild a trie of all needles, add failure links like KMP on a forest, then scan the haystack once — every pattern that ends at the current character reports.
Read MoreEstimate cardinality with a handful of registers and a harmonic mean — plus-or-minus is the point, not a HashSet of every key.
Read MoreAlign the pattern at the window end, use a bad-character skip (and the good-suffix idea) so a late mismatch jumps the haystack instead of sliding by one.
Read MoreRaft terms, leader election, and log replication at awareness depth — enough to know what etcd and Kafka-adjacent consensus are doing, not enough to ship your own cluster.
Read MoreSlide a window hash in O(1), compare hashes first, then verify characters — the procedure for one needle or many needles against the same haystack.
Read MoreA coordinator asks every participant to prepare, then commit or abort together — and why a crashed coordinator leaves the cluster stuck.
Read MoreWait base × 2^attempt after a failure, cap the wait, and add jitter so retries do not stampede the same instant.
Read MoreQueue work into a bucket that leaks at a constant rate — overflow is dropped or the caller waits. Smooth output, not a stored burst of tokens.
Read MoreBuild the LPS prefix table, then scan the text once — on a mismatch the pattern jumps using already-matched prefix, so the text index never retreats.
Read MoreRefill tokens at a steady rate, spend one per request, and allow a burst up to bucket capacity — then reject or wait.
Read MoreGrow a min-heap of crossing edges from a seed until every vertex is in the tree — a Dijkstra-shaped frontier for an MST, not distances from a source.
Read MorePlace keys on a ring so adding or removing a node remaps only its neighbors — not every key — with virtual nodes to even the load.
Read MoreChoose, recurse, undo: search a decision tree with pruning when the next pick depends on the path — not a second knapsack table.
Read MorePick a maximum subset of non-overlapping intervals by earliest finish time — greedy that throws ranges away, not merge-intervals.
Read MoreFind repeated phrases in a sliding window as length-distance pairs, then Huffman-code the tokens — that pairing is DEFLATE, not Huffman alone.
Read MoreBuild a prefix-free code from symbol frequencies with a heap: greedy merges, why it is optimal here, and why this is not DEFLATE.
Read MoreLevenshtein distance on a DP grid: insert, delete, substitute, and recover one alignment — related to LCS, a different job.
Read MoreLongest increasing subsequence: the O(n²) best-ending-here table, then patience / tails plus binary search for n log n.
Read MoreFind the longest common subsequence of two strings with a DP grid: match or skip, then reconstruct one shared sequence.
Read MoreMake change when each denomination may be used again: min-coins and count combinations, and why this is not 0/1 knapsack.
Read MoreFill a capacity with pick-or-skip DP: each item once, a 2D table or a 1D roll, and how to reconstruct which items went in.
Read MoreSort every undirected edge cheapest-first, skip endpoints already in the same Union-Find component, accept the rest until n-1 edges — an MST that is not a shortest path from a source.
Read MoreOrder the heap by f = g + h, settle toward a goal when h never overestimates remaining cost, and skip stale pairs like Dijkstra — the same procedure with a heuristic that may guess low, never high.
Read MoreFill a dense distance matrix by relaxing every triple (k, i, j) — all-pairs shortest paths when n³ is the bill you can pay, and a negative on the diagonal is a negative cycle.
Read MoreRelax every edge V-1 times, then one more pass for a negative cycle — single-source shortest path when a weight is allowed to be negative.
Read MoreGrow a min-heap frontier by current distance, settle each vertex once, and lazy-repush instead of decrease-key — the weighted cousin of BFS when every edge weight is non-negative.
Read MoreDFS to record finish order, transpose the digraph, DFS again in reverse finish order — each second-pass tree is a strongly connected component, and the condensation is a DAG.
Read MoreEmit each vertex only after its predecessors — Kahn with indegree and a queue, or DFS reverse finish times — and treat leftover vertices as a cycle.
Read MoreDetect a directed cycle with 3-color DFS (gray means on the recursion stack) and an undirected cycle by skipping the parent — a visited flag alone is the diamond trap.
Read MoreWalk a graph with DFS, stamp finish times, run the same walk on an ArrayDeque, and recognize a back edge as the shape of a cycle.
Read MoreVisit vertices in hop order with a FIFO queue — level order and unweighted shortest path — and see why a stack is the wrong frontier.
Read MoreSort RAM-sized chunks, write runs to disk, then k-way merge with a heap of heads — the in-memory merge-sort cousin when the file cannot be loaded.
Read MoreNatural runs, insertion on short runs, then merge — what object Arrays.sort and Collections.sort actually run, and why you should not hand-roll it.
Read MoreLSD digit passes as counting sort, when integer or string keys have a digit layout, and why Arrays.sort is not this.
Read MoreHistogram, prefix of counts, and a stable place-from-the-right pass when keys come from a small universe.
Read MoreBuild a max-heap and extract the max into the tail — guaranteed O(n log n), little extra memory, and why PriorityQueue poll-all is not this procedure.
Read MorePartition around a pivot and recurse — and why last-element vs random vs median-of-three vs dual-pivot is the algorithm, not textbook Lomuto as Arrays.sort.
Read MoreSplit, sort the halves, merge two sorted runs — why the extra array buys a guaranteed O(n log n) bound and stability, and what object Arrays.sort actually runs.
Read MoreInsertion still earns a seat on small or nearly-sorted ranges; selection swaps the min into place; bubble is a whiteboard name — none of them are the production default.
Read MoreSort by start, sweep, and merge overlapping calendar or busy ranges — and when this is not interval scheduling.
Read MoreRunning best ending here, empty-array and all-negative pitfalls, and why this is one pass of DP you do not need to name as a table.
Read MoreInclusive vs exclusive prefixes, a 2D sketch, difference arrays for range updates, and when a Fenwick or segment tree is the next bill.
Read MoreFixed and variable windows, the add-right / drop-left invariant, and why this is not the same thing as a rate-limit window.
Read MoreOpposite-end, pair-sum on sorted data, and fast/slow — when two indexes replace O(n²) and when they are just two indexes.
Read MoreThe sorted invariant, lower and upper bound, off-by-one, and what Arrays.binarySearch encodes when the key is missing.
Read MoreA map of search, sort, graphs, strings, DP, and systems algorithms — what job each one solves, when to skip it, and a living index of every post in this series.
Read More