Quickselect for the Kth Largest Element
Find the kth largest element in average linear time with quickselect, avoiding the cost of fully sorting when only one rank is needed.
Page 6 of 14
Find the kth largest element in average linear time with quickselect, avoiding the cost of fully sorting when only one rank is needed.
Build point-free data transformation pipelines with Ramda compose, lens-based updates, and curried predicates that stay testable end to end.
Enforce a distributed rate limit with rate-limiter-flexible backed by Redis points, insurance fallback, and per-key consumption tracking.
Render React server-side to a node stream with Suspense boundaries so fast content flushes first and slow data streams in without blocking.
Build a Redis-backed caching layer with TTL eviction, LRU maxmemory policy, cache-aside reads, and explicit invalidation on writes.
Wrap flaky operations with the retry package using predicate-based retries, exponential factors, randomization, and per-operation abort signals.
Retry a flaky async operation a bounded number of times, doubling the delay between attempts, adding jitter, and only retrying errors that are safe to repeat.
Enforce least-privilege access with composable role middleware that verifies tokens, resolves roles, and gates routes without inline checks.
Limit how many callers may hold a resource at once with a counted semaphore that queues waiters and releases permits fairly.
Track request timestamps in a sliding window to count how many calls happened in the last interval, rejecting requests that exceed the allowed rate.
Build dynamic IN clauses with generated placeholders instead of string interpolation, keeping every user value bound as a statement parameter.
Speed up static site builds by hashing content inputs per page, reusing unchanged build cache entries, and invalidating only affected pages.
Process a text stream line by line with a transform, keeping partial chunks buffered so splitting on newlines does not corrupt records.
Consume newline-delimited JSON streams line by line using async iteration over the response body, parsing each record with error isolation.
Query a Supabase table with typed client filters, range pagination, upsert conflicts, and realtime subscription cleanup in one flow.
Use Superagent to GET and POST with automatic parsing, retries, timeout control, and typed response body access for JSON and form payloads.
Throttle limits how often a function runs by allowing at most one call per interval, useful for scroll and resize handlers that fire continuously.
Order a dependency graph so every node appears after its prerequisites, reporting a cycle when no valid order exists.
Create an undici Agent with per-origin connection limits and pipelining depth, then dispatch pooled HTTP requests with explicit abort timeouts.
Write Vitest unit tests for an Express app with Supertest, covering success paths, validation errors, and HTTP status assertions per case.
Keep a WebSocket client alive through disconnects with exponential backoff reconnect, jitter, heartbeat pings, and a bounded retry budget.
Rotate application logs by day and size with winston-daily-rotate-file, keeping bounded history, zipped archives, and separate error streams.
Parse and validate process.env at boot with a Zod schema so missing or malformed configuration fails fast before any request is served.
Instrument aiohttp with middleware that logs every request with duration, status, and client identity, sampling noisy health probes.
Download large files with aiohttp while iterating response chunks, hashing each block on the fly and keeping memory usage flat.
Run many async coroutines while capping concurrency with a semaphore, avoiding the flood of pending tasks that unbounded gathering creates.
Throttle a fast producer with a bounded asyncio queue, blocking enqueue when consumers fall behind instead of buffering unbounded data.
Fan out concurrent work with asyncio TaskGroup, wrapping the group in wait_for so one timeout cancels every straggler cleanly.
Bulk load millions of rows into PostgreSQL with asyncpg COPY, streaming records from an async generator with a single protocol message.
Use a Bloom filter to rule out absent keys with no false negatives, trading a small false-positive rate for large memory savings.
Schedule recurring Celery tasks with beat crontabs, mixing timezones, staggered offsets, and task-specific routing to dedicated queues.
Retry failing Celery tasks with exponential backoff and jitter, capping max delay, classifying retryable exceptions, and exposing stats.
Build chained Click subcommands where multiple steps run in sequence, sharing a result context and enforcing invocation order.
Wrap a code block in a context manager that measures elapsed time, so timing instrumentation is added without clutter or manual bookkeeping.
Write dictionaries to CSV with a declared header order, ensuring every row has the same columns even when fields are missing.
Paginate a query by comparing against the last seen key instead of a numeric offset, so pages stay stable when rows are inserted.
Scale pandas aggregations with Dask partitions, letting the scheduler parallelize map-side work and tree-reduce the shuffled results.
Validate invariants in a dataclass post-init hook so invalid instances cannot be constructed, keeping bad data out of the rest of the system.
Recursively merge configuration dictionaries so nested sections are combined rather than replaced wholesale by a later override.
Manage containers programmatically with the Docker SDK for Python, configuring health checks and waiting for healthy status before routing.
Read required and optional settings from the environment with typed defaults, raising a clear error when a required value is missing.
Wrap handler functions in a decorator that converts known exceptions into structured error results while letting unexpected errors propagate.
Provide shared settings through a FastAPI dependency so handlers receive a configured object and tests can override it cleanly.
Issue short-lived access tokens plus rotating refresh tokens in FastAPI, detecting reuse of revoked tokens on every exchange.
Expose cursor-based pagination in FastAPI with stable keyset queries, opaque cursor tokens, and total-count-free responses.
Manage shared resources with FastAPI lifespan context, wiring async clients into dependency injection with clean startup and shutdown.
Stream large multipart uploads in FastAPI with per-part size caps, allowed content types, and chunked writes that never buffer fully.
Manage WebSocket connections in FastAPI with a connection registry, broadcasting to all clients and isolating slow consumers.
Accelerate pure lookups with functools.lru_cache, sizing maxsize from hit rates and isolating unhashable arguments.
Consume an iterable in fixed-size batches with a generator, processing large streams without loading everything into memory.
Find the fewest hops between two nodes with breadth-first search, reconstructing the path and reporting when no route exists.
Subclass the HTTPX transport layer to retry idempotent requests with capped backoff, honoring Retry-After and exponential delays.
Add a persistent caching layer to httpx with httpx-cache, replaying stale responses offline and refreshing in the background.
Test HTTP clients without a network by swapping in httpx MockTransport, scripting responses per URL and asserting request payloads.
Sign expiring action tokens with itsdangerous, binding purpose and user context so reset links cannot be replayed cross-endpoint.
Decode newline-delimited JSON records from a file or socket one line at a time, reporting the offending line when a record fails to parse.
Apply a bounded least-recently-used cache to a pure function so repeated calls with the same arguments skip recomputation.
Validate deeply nested payloads with Marshmallow schemas, mapping field errors to their dotted paths and applying load-time defaults.
Run aggregation pipelines with the async Motor driver, streaming large result sets via async iteration and cursor batching.
Trace FastAPI request flows with OpenTelemetry, creating spans for routes and internal steps, then exporting OTLP batches to a collector.
Aggregate CSV files larger than memory with pandas chunksize iteration, accumulating partial sums and merging into a final report.
Hash passwords with Argon2id through passlib, storing algorithm parameters inline so upgrades rehash transparently on next login.
Write files atomically with pathlib by staging content to a temp file in the same directory and renaming over the target on success.
Run Polars lazy frames so predicate pushdown, projection pruning, and streaming execution optimize the plan before any data moves.
Normalize messy form input with Pydantic field validators, trimming strings, coercing digit strings, and rejecting malformed values early.
Describe a request payload with a Pydantic model so types and constraints are enforced and clear validation errors are returned automatically.
Load typed configuration from environment variables with pydantic-settings, layering dotenv files and validating on import.
Watch MongoDB collection changes with PyMongo, persisting resume tokens so listeners recover exactly where they left off after restart.
Share async resources across tests with pytest-asyncio fixtures, scoping engine creation per session and cleaning up deterministically.
Provide a pytest fixture that creates a fresh database per test and tears it down, so tests stay independent and order does not matter.
Configure Python logging with rotation by size and backups, per-module loggers, structured formatting, and a root-level filter guard.
Implement a token bucket that refills at a steady rate and allows short bursts, a standard algorithm for shaping request traffic.
Cache async function results in Redis with a decorator, TTL expiry, single-flight locking, and JSON serialization per call signature.
Connect through Redis Sentinel for automatic failover, detecting role changes, retrying reads on replicas, and fencing split-brain writes.
Decorate a function so transient exceptions are retried a fixed number of times with growing delay, keeping call sites free of retry plumbing.
Render dynamic CLI tables with Rich Live mode, updating rows in place as background tasks progress and finishing with a clean summary.
Generate cryptographically secure tokens with the secrets module, comparing them in constant time and binding usage scope per token.
Throttle FastAPI endpoints with SlowAPI using a Redis backend, per-user limits, custom headers, and exempted internal callers.
Drive async SQLAlchemy sessions with pooled engines, per-request session scopes, and transaction guards that always release connections.
Set per-session isolation levels in SQLAlchemy, using repeatable read for consistent reports and read committed for regular traffic.
Open a SQLite connection as a context manager so transactions commit on success and roll back on error, and the connection always closes.
Define a GraphQL schema with Strawberry on FastAPI, writing typed resolvers for queries and mutations with context dependency injection.
Bind request-scoped context with structlog, so every log line carries correlation fields without threading state through call stacks.
Configure a JSON formatter so every log record carries consistent fields, making logs searchable and correlatable across services.
Guard a flaky dependency with a circuit breaker state machine, falling back to cached defaults and opening after repeated failures.
Compose retry behavior with Tenacity using stop conditions, adaptive wait strategies, custom retry predicates, and typed final errors.
Build async CLI commands with Typer, combining type-annotated options, enum choices, environment fallbacks, and per-command validation.
Configure uvicorn worker shutdown with timeout windows, draining in-flight requests and cancelling background loops cleanly on signals.
Enrich errors with anyhow context layers, converting foreign error types into chains that print root causes and section context.
Hash passwords with argon2id at tuned cost parameters, verifying in constant time with encoded salt and version metadata.
Accept multipart uploads in Axum with per-field size caps, MIME allowlists, and streaming field reads that cap total request bytes.
Stream large responses from an async generator into the response body, applying timeouts per chunk and clean cancellation.
Instrument Axum with a tower middleware layer that measures request durations, stamps request ids, and logs completions.
Build complex values step by step with consuming methods that return Self, so an incomplete configuration cannot be constructed accidentally.
Keep a fixed-capacity least-recently-used cache with the lru crate, evicting the coldest entry and promoting reads automatically.
Define a CLI interface with clap derives so arguments are parsed, validated, and documented from one struct declaration.
Define a clap CLI with typed subcommands, layered defaults, optional config file overrides, and environment variable fallbacks.
Chain pipeline stages with crossbeam bounded channels, applying backpressure from slow consumers and draining on shutdown.
Stream CSV files record by record with the csv crate, validating deserialization per row and quarantining malformed lines.
Implement the Iterator trait to produce a lazy Fibonacci sequence, showing how infinity can be represented without allocating a collection.