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 MorePosts September 2026
79 posts
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 MoreA decision guide for the Java Collections series: given the hot operation, null policy, encounter order, and whether another thread looks — which JDK type to new.
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 MoreLearn how Java 21 sequenced collections provide uniform first, last, and reversed operations across lists, deques, ordered sets, and ordered maps.
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 MoreModel a tiny promo DSL as AND/OR of percent-off and sku-in-category expressions that evaluate(Order), and skip it when a few ifs or a real parser would be honest.
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 MoreAdd CSV export and tax walks to a stable Sku / Category tree with accept(Visitor) so each new report is a class, not another method on every catalog type.
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 MoreClone a configured DiscountPolicy, ChargeRequest, or gateway test double in Java instead of rebuilding constructor arguments — and skip clone() when new is cheaper or the copy shares mutable guts.
Read MoreA coordinator asks every participant to prepare, then commit or abort together — and why a crashed coordinator leaves the cluster stuck.
Read MoreUndo a checkout draft in Java by letting Order take an opaque snapshot — no public fields, no JSON dump, and no serializing OrderProcessor.
Read MoreStop DiscountPolicy, PaymentGateway, fraud, inventory, and the notifier from importing each other by letting CheckoutMediator own the checkout conversation.
Read MoreWait base × 2^attempt after a failure, cap the wait, and add jitter so retries do not stampede the same instant.
Read MoreShare immutable catalog SKU metadata across cart LineItems so a Black Friday order does not clone name, tax class, and image URL on every row.
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 MoreStop the Email×SendGrid / SMS×Twilio subclass grid by letting OrderNotifier hold a MessageSender so channels and vendors vary independently.
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 MoreStop walking Order line items with get(i) on a leaked ArrayList so a switch from list to a SKU tree does not rewrite OrderProcessor.
Read MoreRefill tokens at a steady rate, spend one per request, and allow a burst up to bucket capacity — then reject or wait.
Read MoreBuild Stripe-region and Razorpay-region checkout families in Java so gateway, webhook parser, and money type vary together without OrderProcessor naming the concretes.
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 MoreReplace a hard-coded fraud-inventory-payment-notify sequence with a Handler chain in Java so a new checkout step is a class you splice in, not a next-type you edit.
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 MoreReplace a growing DRAFT / PAID / REFUNDED / VOID switch in process, refund, and void with OrderStatus objects that own legal transitions, so OrderProcessor stops being the state machine.
Read MoreChoose, recurse, undo: search a decision tree with pruning when the next pick depends on the path — not a second knapsack table.
Read MoreReplace nested loops over Outdoor / Hiking / SKUs with a CatalogNode tree so a category and a single product both answer subtotal(), and OrderProcessor still charges one payable.
Read MorePut a PaymentGateway proxy in front of a slow SDK so OrderProcessor still calls charge, while lazy init, an auth check, and a last-result cache decide whether the real gateway runs.
Read MoreHands-on strace recipes — attach to a PID, follow children, filter syscalls, and read the wait that logs never mentioned.
Read MorePick a maximum subset of non-overlapping intervals by earliest finish time — greedy that throws ranges away, not merge-intervals.
Read MoreTurn charge, refund, and capture into Java objects you can queue, retry, undo, or audit — without wrapping a one-shot process() in ceremony.
Read MoreHands-on tar and gzip recipes — create an archive, inspect it before extract, compress with gzip, and restore without clobbering the wrong tree.
Read MoreHide checkout’s discount, payment, fraud, and tax conversation behind one CheckoutFacade.place(Order) so controllers stop assembling the subsystem.
Read MoreTry JEP 532 in JDK 27: use primitive patterns with instanceof, switch directly on long, float, double, and boolean, and reject lossy conversions without hand-written casts.
Read MoreHands-on text-prep recipes — slice columns, sort keys, count uniques, and translate characters before you reach for awk or sed.
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 MoreFreeze a shared Java payment sequence so capture, refund, and void keep one skeleton and only the provider step (and hooks) vary.
Read MoreHands-on SSH recipes — keys and config, copy files with scp, and tunnel a port without memorizing every flag.
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 MoreKeep a process-wide resource as an enum singleton only when you can name why there must be one, and inject Clock, config, and gateways into OrderProcessor instead of AppContext.getInstance().
Read MoreTry JEP 531 in JDK 27: LazyConstant.of, List/Map/Set.ofLazy, and one-time thread-safe init the JIT can constant-fold — without double-checked locking.
Read MoreHands-on crontab and systemd timer recipes — schedule a job, choose calendar vs boot delays, and find the run that never fired.
Read MoreLevenshtein distance on a DP grid: insert, delete, substitute, and recover one alignment — related to LCS, a different job.
Read MoreReplace a telescoping ChargeRequest constructor with a Java builder so required checkout fields stay required, optional ones stay optional, and the product can still be a record.
Read MoreHands-on systemctl recipes for everyday work — inspect units, start and stop services, enable at boot, and debug failed units without guessing.
Read MoreWrap a vendor client whose methods do not match PaymentGateway so OrderProcessor keeps calling charge(Order, BigDecimal) and never learns PayPal’s shape.
Read MoreHands-on git bisect — binary-search commits to find the first one that broke a working check, then reset HEAD and optionally automate the walk.
Read MoreCopy one commit onto another branch — bring a hotfix from main onto your feature without merging the rest of main.
Read MoreOpen a pull request, read the host diff, merge on GitHub or GitLab, then pull main locally so review happens before the default branch moves.
Read MoreHands-on Git rebase — fetch an updated main, replay your feature commits on top of it, and skip the extra merge commit.
Read MoreHands-on Git — recover a commit after a reset that went too far, using git reflog to restore HEAD or create a recovery branch.
Read MoreHands-on Git stash — park a dirty working tree, switch branches, and restore the work without a fake WIP commit.
Read MoreImplement equals and hashCode so HashMap and HashSet can find the key you put — Object contract, records, and why a mutable id loses the entry.
Read MoreChoose throw over a sentinel return, close resources with try-with-resources, and wrap checked exceptions at lambda boundaries instead of swallowing them.
Read MoreUse Java generics so List of Order stays a list of orders — type parameters, PECS, erasure, and why raw types still compile.
Read MoreProve an Order pricing rule with plain JUnit 5 — assertions, parameterized tests, and lifecycle — before you reach for a Spring test slice.
Read MoreUse Path and Files to read, copy, and walk directories in the JVM — without new File soup and without turning this into a Linux CLI tutorial.
Read MoreCache order reads with Spring @Cacheable and in-process Caffeine, evict on update, and keep JPA entities out of the cache.
Read MoreVersion the orders schema with Flyway SQL migrations, turn off Hibernate ddl-auto outside local experiments, and prove the script with Testcontainers.
Read MoreTurn Bean Validation failures and domain exceptions into RFC 7807 ProblemDetail responses with @ControllerAdvice so API clients get a body they can actually use.
Read MoreSplit Spring Boot config by profile, bind settings to a @ConfigurationProperties record, and inject secrets from the environment instead of committing them in the jar.
Read MoreReplace ad-hoc HTTP calls with Spring Boot 3 RestClient: inject the managed Builder, set timeouts, map JSON to records, and handle status codes without RestTemplate ceremony.
Read MoreLongest increasing subsequence: the O(n²) best-ending-here table, then patience / tails plus binary search for n log n.
Read MoreReplace AuditedRetryingCachedGateway subclasses with PaymentGateway wrappers you compose at the edge — logging, retry, cache — without a new type per combination.
Read MoreFind the longest common subsequence of two strings with a DP grid: match or skip, then reconstruct one shared sequence.
Read MoreStop editing OrderProcessor for every new notification channel by publishing a payment event and letting EmailNotifier and AuditLog subscribe.
Read MoreMove construction of DiscountPolicy and PaymentGateway behind a polymorphic creator so six controllers stop naming PercentOff and StripeGateway.
Read MoreWhat the Java 27 PEM API is (JEP 538): encode and decode keys, certificates, and CRLs with PEMEncoder and PEMDecoder — no BouncyCastle, no sun.security.util.
Read MoreMake change when each denomination may be used again: min-coins and count combinations, and why this is not 0/1 knapsack.
Read MoreReplace a growing discount if/else with a Strategy in Java so each new promotion is a class you add, not a branch you edit into OrderProcessor.
Read MoreWhat Leyden AOT caches are (JEP 483, 514, 515, 516): train a HotSpot cache, then start faster and warm up sooner — still a JVM, not a GraalVM native image.
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 MoreA map of creational, structural, and behavioral patterns — what pain each one solves, when to skip it, and links to every post in this series.
Read MoreWhat Java 27 JEP 527 is: hybrid ML-KEM + ECDHE named groups in TLS 1.3 so JSSE sessions survive store-now-decrypt-later — without writing crypto.
Read More