Skip to main content

Advanced JavaScript Problems 201–300

Treat each exercise as production design: define ownership, cancellation, retries, backpressure, security boundaries, observability and proof of correctness before implementation.

201. Async Mutex

Difficulty: Advanced · Category: Concurrency

Problem statement: Implement a fair mutex with acquire, release and AbortSignal cancellation.

Input: concurrent functions

Output: serialized critical sections

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: A acquires before B → B waits

Hint: Identify the invariant or transformation first; queue deferred acquirers and transfer ownership exactly once.

Recommended approach: Queue deferred acquirers and transfer ownership exactly once.

Complexity: O(1) average queue operations and O(waiters) space.

Solution explanation

Queue deferred acquirers and transfer ownership exactly once. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average queue operations and O(waiters) space.

202. Semaphore with Permits

Difficulty: Advanced · Category: Concurrency

Problem statement: Implement a fair counting semaphore with cancellation and scoped release.

Input: permit count and tasks

Output: bounded concurrency

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: 3 permits with 10 tasks → max 3 running

Hint: Identify the invariant or transformation first; queue weighted requests and return idempotent release functions.

Recommended approach: Queue weighted requests and return idempotent release functions.

Complexity: O(waiters) scheduling and O(waiters) space.

Solution explanation

Queue weighted requests and return idempotent release functions. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(waiters) scheduling and O(waiters) space.

203. Read Write Lock

Difficulty: Advanced · Category: Concurrency

Problem statement: Allow concurrent readers or one writer with a documented fairness policy.

Input: read/write acquisitions

Output: lock grants

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: two readers then writer → writer waits

Hint: Identify the invariant or transformation first; track active readers, writer and queued requests.

Recommended approach: Track active readers, writer and queued requests.

Complexity: O(queue) policy cost and O(waiters) space.

Solution explanation

Track active readers, writer and queued requests. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(queue) policy cost and O(waiters) space.

204. Priority Task Scheduler

Difficulty: Advanced · Category: Concurrency

Problem statement: Schedule async tasks by priority and FIFO order with starvation protection.

Input: tasks priorities limit

Output: settled outcomes

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: old low priority eventually runs

Hint: Identify the invariant or transformation first; use a heap plus aging or weighted queues.

Recommended approach: Use a heap plus aging or weighted queues.

Complexity: O(log n) enqueue/dequeue and O(n) space.

Solution explanation

Use a heap plus aging or weighted queues. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log n) enqueue/dequeue and O(n) space.

205. Token Bucket Rate Limiter

Difficulty: Advanced · Category: Concurrency

Problem statement: Implement a token bucket with refill, bursts and injectable monotonic clock.

Input: rate capacity requests

Output: allow or wait

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: capacity5 sixth immediate → denied

Hint: Identify the invariant or transformation first; refill by elapsed time and consume atomically.

Recommended approach: Refill by elapsed time and consume atomically.

Complexity: O(1) per request and O(1) space.

Solution explanation

Refill by elapsed time and consume atomically. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) per request and O(1) space.

206. Circuit Breaker

Difficulty: Advanced · Category: Reliability

Problem statement: Wrap an async dependency with closed, open and half-open states.

Input: operation policy

Output: guarded operation

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: repeated failures → fast reject then probe

Hint: Identify the invariant or transformation first; use rolling failure thresholds and one controlled half-open probe.

Recommended approach: Use rolling failure thresholds and one controlled half-open probe.

Complexity: O(1) per call and O(window) space.

Solution explanation

Use rolling failure thresholds and one controlled half-open probe. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) per call and O(window) space.

207. Retry Budget

Difficulty: Advanced · Category: Reliability

Problem statement: Limit retries as a fraction of successful traffic over a moving window.

Input: request outcomes

Output: retry allowed Boolean

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: excess failures → retries denied

Hint: Identify the invariant or transformation first; track bounded buckets of successes and retries.

Recommended approach: Track bounded buckets of successes and retries.

Complexity: O(1) amortized and O(bucket count) space.

Solution explanation

Track bounded buckets of successes and retries. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) amortized and O(bucket count) space.

208. Bulkhead Executor

Difficulty: Advanced · Category: Reliability

Problem statement: Isolate workloads into separate bounded concurrency pools.

Input: classed tasks

Output: isolated results

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: slow reports do not block checkout

Hint: Identify the invariant or transformation first; route by class to independent queues with limits.

Recommended approach: Route by class to independent queues with limits.

Complexity: O(1) routing plus queue costs.

Solution explanation

Route by class to independent queues with limits. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) routing plus queue costs.

209. Idempotency Key Store

Difficulty: Advanced · Category: Reliability

Problem statement: Coordinate duplicate mutation requests and replay the first completed result.

Input: key request hash operation

Output: shared result

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: same payment key twice → one execution

Hint: Identify the invariant or transformation first; atomically reserve key and persist status/result with expiry.

Recommended approach: Atomically reserve key and persist status/result with expiry.

Complexity: O(1) average storage operations and O(keys) space.

Solution explanation

Atomically reserve key and persist status/result with expiry. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average storage operations and O(keys) space.

210. Outbox Processor

Difficulty: Advanced · Category: Reliability

Problem statement: Process durable outbox events with leases, retries and idempotent publication.

Input: outbox rows worker

Output: publication states

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: worker crash → lease expires and retries

Hint: Identify the invariant or transformation first; claim batches transactionally and mark published after acknowledgement.

Recommended approach: Claim batches transactionally and mark published after acknowledgement.

Complexity: O(n log n) scheduling depending storage.

Solution explanation

Claim batches transactionally and mark published after acknowledgement. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n log n) scheduling depending storage.

211. Async Iterator Merge

Difficulty: Advanced · Category: Async Iteration

Problem statement: Merge multiple async iterables as values become available with cancellation.

Input: iterables and signal

Output: merged async sequence

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: slow A fast B → B may yield first

Hint: Identify the invariant or transformation first; race one pending next call per source and replenish winner.

Recommended approach: Race one pending next call per source and replenish winner.

Complexity: O(sources) active Promises and O(sources) space.

Solution explanation

Race one pending next call per source and replenish winner. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(sources) active Promises and O(sources) space.

212. Async Iterator Zip

Difficulty: Advanced · Category: Async Iteration

Problem statement: Zip async iterables until the shortest completes and close the rest.

Input: async iterables

Output: tuple sequence

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: A1,A2 and B1 → [A1,B1]

Hint: Identify the invariant or transformation first; await next values concurrently and call return on remaining iterators.

Recommended approach: Await next values concurrently and call return on remaining iterators.

Complexity: O(k) per tuple and O(k) space.

Solution explanation

Await next values concurrently and call return on remaining iterators. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(k) per tuple and O(k) space.

213. Backpressured Event Stream

Difficulty: Advanced · Category: Streams

Problem statement: Convert an event source into a bounded async iterable with overflow policy.

Input: event target capacity

Output: async sequence

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: burst beyond capacity → drop or error policy

Hint: Identify the invariant or transformation first; buffer to capacity, resolve waiters and detach on close.

Recommended approach: Buffer to capacity, resolve waiters and detach on close.

Complexity: O(1) average and O(capacity) space.

Solution explanation

Buffer to capacity, resolve waiters and detach on close. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average and O(capacity) space.

214. Line Transform Stream

Difficulty: Advanced · Category: Streams

Problem statement: Implement a TransformStream that emits complete text lines across arbitrary chunks.

Input: text chunks

Output: lines

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: ab then c newline → abc

Hint: Identify the invariant or transformation first; carry an incomplete suffix and flush at stream end.

Recommended approach: Carry an incomplete suffix and flush at stream end.

Complexity: O(total bytes) time and O(max line) space.

Solution explanation

Carry an incomplete suffix and flush at stream end. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(total bytes) time and O(max line) space.

215. Streaming JSON Lines Parser

Difficulty: Advanced · Category: Streams

Problem statement: Parse and validate JSONL incrementally with row-numbered errors.

Input: byte stream schema

Output: records or issues

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: two lines one invalid → one record one issue

Hint: Identify the invariant or transformation first; decode, split lines, JSON.parse each and apply schema.

Recommended approach: Decode, split lines, JSON.parse each and apply schema.

Complexity: O(bytes) time and bounded line memory.

Solution explanation

Decode, split lines, JSON.parse each and apply schema. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(bytes) time and bounded line memory.

216. Streaming CSV State Machine

Difficulty: Advanced · Category: Parsing

Problem statement: Parse quoted CSV across chunks, including escaped quotes and newlines.

Input: text chunks

Output: rows

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: quoted newline field → one cell

Hint: Identify the invariant or transformation first; maintain field, row and quote state between chunks.

Recommended approach: Maintain field, row and quote state between chunks.

Complexity: O(bytes) time and O(max row) memory.

Solution explanation

Maintain field, row and quote state between chunks. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(bytes) time and O(max row) memory.

217. Incremental UTF-8 Decoder

Difficulty: Advanced · Category: Binary Data

Problem statement: Decode split UTF-8 bytes without corrupting multi-byte characters.

Input: Uint8Array chunks

Output: strings

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: split emoji bytes → one emoji

Hint: Identify the invariant or transformation first; use TextDecoder streaming mode and final flush.

Recommended approach: Use TextDecoder streaming mode and final flush.

Complexity: O(bytes) time and O(chunk text) space.

Solution explanation

Use TextDecoder streaming mode and final flush. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(bytes) time and O(chunk text) space.

218. Binary Protocol Reader

Difficulty: Advanced · Category: Binary Data

Problem statement: Parse length-prefixed binary frames safely from partial chunks.

Input: byte chunks

Output: frames

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: length4 plus data → one frame

Hint: Identify the invariant or transformation first; accumulate bounded buffer, read DataView header and emit complete frames.

Recommended approach: Accumulate bounded buffer, read DataView header and emit complete frames.

Complexity: O(bytes) time and O(max buffered frame) space.

Solution explanation

Accumulate bounded buffer, read DataView header and emit complete frames. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(bytes) time and O(max buffered frame) space.

219. Transferable Worker Pool

Difficulty: Advanced · Category: Workers

Problem statement: Distribute CPU tasks to Web Workers with transferable buffers, cancellation and crash recovery.

Input: jobs worker count

Output: results

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: large buffer job → ownership transferred

Hint: Identify the invariant or transformation first; track idle workers and job IDs, transfer inputs and respawn failures.

Recommended approach: Track idle workers and job IDs, transfer inputs and respawn failures.

Complexity: O(jobs) scheduling and bounded worker memory.

Solution explanation

Track idle workers and job IDs, transfer inputs and respawn failures. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(jobs) scheduling and bounded worker memory.

220. Worker Map Reduce

Difficulty: Advanced · Category: Workers

Problem statement: Partition a numeric dataset across workers and combine partial aggregates.

Input: TypedArray workers reducer

Output: aggregate

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: million values → sum

Hint: Identify the invariant or transformation first; split contiguous ranges, transfer/copy deliberately and reduce partials.

Recommended approach: Split contiguous ranges, transfer/copy deliberately and reduce partials.

Complexity: O(n/p plus p) time and O(p) result space.

Solution explanation

Split contiguous ranges, transfer/copy deliberately and reduce partials. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n/p plus p) time and O(p) result space.

221. SharedArray Ring Buffer

Difficulty: Advanced · Category: Shared Memory

Problem statement: Design a single-producer single-consumer ring buffer with Atomics.

Input: SharedArrayBuffer capacity

Output: enqueue/dequeue

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: producer writes then consumer reads

Hint: Identify the invariant or transformation first; use atomic head/tail indices and defined memory ordering.

Recommended approach: Use atomic head/tail indices and defined memory ordering.

Complexity: O(1) per operation and O(capacity) space.

Solution explanation

Use atomic head/tail indices and defined memory ordering. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) per operation and O(capacity) space.

222. AbortSignal Tree

Difficulty: Advanced · Category: Cancellation

Problem statement: Compose parent, timeout and local cancellation while preserving the first reason.

Input: signals

Output: combined signal

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: parent abort → child abort same reason

Hint: Identify the invariant or transformation first; use AbortSignal.any or listeners with once cleanup.

Recommended approach: Use AbortSignal.any or listeners with once cleanup.

Complexity: O(signals) setup and O(signals) listeners.

Solution explanation

Use AbortSignal.any or listeners with once cleanup. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(signals) setup and O(signals) listeners.

223. Structured Concurrency Scope

Difficulty: Advanced · Category: Concurrency

Problem statement: Run child async tasks so success waits all and failure aborts siblings.

Input: task callbacks and parent signal

Output: results or aggregate error

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: one child fails → peers aborted

Hint: Identify the invariant or transformation first; create child controller, start tasks, abort on failure and await settlement.

Recommended approach: Create child controller, start tasks, abort on failure and await settlement.

Complexity: O(children) scheduling and O(children) space.

Solution explanation

Create child controller, start tasks, abort on failure and await settlement. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(children) scheduling and O(children) space.

224. Promise Deduplication Cache

Difficulty: Advanced · Category: Caching

Problem statement: Share one in-flight Promise per key and remove or retain it according to outcome policy.

Input: key async loader

Output: shared Promise

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: two same loads → one loader call

Hint: Identify the invariant or transformation first; store pending Promise before awaiting and clean in finally or cache success.

Recommended approach: Store pending Promise before awaiting and clean in finally or cache success.

Complexity: O(1) average lookup and O(keys) space.

Solution explanation

Store pending Promise before awaiting and clean in finally or cache success. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average lookup and O(keys) space.

225. Stale While Revalidate Cache

Difficulty: Advanced · Category: Caching

Problem statement: Serve fresh/stale cached data while one background refresh updates it.

Input: key loader freshness windows

Output: value metadata

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: stale entry → immediate stale plus refresh

Hint: Identify the invariant or transformation first; track timestamps and deduplicate refresh Promises.

Recommended approach: Track timestamps and deduplicate refresh Promises.

Complexity: O(1) average lookup and O(keys) space.

Solution explanation

Track timestamps and deduplicate refresh Promises. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average lookup and O(keys) space.

226. Two Tier Cache

Difficulty: Advanced · Category: Caching

Problem statement: Combine memory LRU and persistent storage with coherent invalidation.

Input: key loader memory disk

Output: value

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: memory miss disk hit → promote

Hint: Identify the invariant or transformation first; read tiers in order and write through with versioned keys.

Recommended approach: Read tiers in order and write through with versioned keys.

Complexity: O(1) memory plus storage latency and bounded memory.

Solution explanation

Read tiers in order and write through with versioned keys. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) memory plus storage latency and bounded memory.

227. Cache Stampede Protection

Difficulty: Advanced · Category: Caching

Problem statement: Prevent many callers from recomputing an expired hot key simultaneously.

Input: key loader

Output: shared refreshed value

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: 100 expiry hits → one refresh

Hint: Identify the invariant or transformation first; use per-key lock or in-flight Promise and optional probabilistic early refresh.

Recommended approach: Use per-key lock or in-flight Promise and optional probabilistic early refresh.

Complexity: O(1) average and O(active keys) space.

Solution explanation

Use per-key lock or in-flight Promise and optional probabilistic early refresh. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average and O(active keys) space.

228. Dependency Graph Resolver

Difficulty: Advanced · Category: Graphs

Problem statement: Resolve package execution order and report a useful cycle path.

Input: nodes dependencies

Output: order or cycle

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: A→B→A → cycle A,B,A

Hint: Identify the invariant or transformation first; dFS with recursion stack and parent links or Kahn plus cycle extraction.

Recommended approach: DFS with recursion stack and parent links or Kahn plus cycle extraction.

Complexity: O(V+E) time and O(V) space.

Solution explanation

DFS with recursion stack and parent links or Kahn plus cycle extraction. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(V+E) time and O(V) space.

229. Incremental Topological Update

Difficulty: Advanced · Category: Graphs

Problem statement: Update a dependency order after adding an edge without always recomputing everything.

Input: DAG order new edge

Output: new order or cycle

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: add C→A → reordered

Hint: Identify the invariant or transformation first; validate reachability then move affected interval nodes.

Recommended approach: Validate reachability then move affected interval nodes.

Complexity: O(V+E) worst time and O(V) space.

Solution explanation

Validate reachability then move affected interval nodes. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(V+E) worst time and O(V) space.

230. Strongly Connected Components

Difficulty: Advanced · Category: Graphs

Problem statement: Return strongly connected components in a directed graph.

Input: adjacency

Output: components

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: A↔B,C → [A,B],[C]

Hint: Identify the invariant or transformation first; use Tarjan low-link indices and stack.

Recommended approach: Use Tarjan low-link indices and stack.

Complexity: O(V+E) time and O(V) space.

Solution explanation

Use Tarjan low-link indices and stack. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(V+E) time and O(V) space.

231. Bellman Ford

Difficulty: Advanced · Category: Graphs

Problem statement: Compute shortest paths with negative edges and detect reachable negative cycles.

Input: weighted edges source

Output: distances or cycle

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: negative edge no cycle → distances

Hint: Identify the invariant or transformation first; relax all edges V-1 times then test one more pass.

Recommended approach: Relax all edges V-1 times then test one more pass.

Complexity: O(VE) time and O(V) space.

Solution explanation

Relax all edges V-1 times then test one more pass. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(VE) time and O(V) space.

232. A Star Grid Path

Difficulty: Advanced · Category: Graphs

Problem statement: Find a low-cost grid path using an admissible heuristic.

Input: grid costs start goal

Output: path

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: open grid → near-direct path

Hint: Identify the invariant or transformation first; use min heap by g plus heuristic and predecessor map.

Recommended approach: Use min heap by g plus heuristic and predecessor map.

Complexity: O(E log V) typical and O(V) space.

Solution explanation

Use min heap by g plus heuristic and predecessor map. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(E log V) typical and O(V) space.

233. Bidirectional BFS

Difficulty: Advanced · Category: Graphs

Problem statement: Find shortest path in an unweighted graph by searching from both ends.

Input: graph start goal

Output: path

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: long chain → meet near middle

Hint: Identify the invariant or transformation first; expand the smaller frontier and detect intersection.

Recommended approach: Expand the smaller frontier and detect intersection.

Complexity: O(b^(d/2)) conceptual time and space.

Solution explanation

Expand the smaller frontier and detect intersection. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(b^(d/2)) conceptual time and space.

234. Floyd Warshall

Difficulty: Advanced · Category: Graphs

Problem statement: Compute all-pairs shortest paths and detect negative cycles.

Input: weight matrix

Output: distance matrix

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: 3-node graph → all distances

Hint: Identify the invariant or transformation first; dynamic program through each intermediate vertex.

Recommended approach: Dynamic program through each intermediate vertex.

Complexity: O(V³) time and O(V²) space.

Solution explanation

Dynamic program through each intermediate vertex. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(V³) time and O(V²) space.

235. Max Flow Edmonds Karp

Difficulty: Advanced · Category: Graphs

Problem statement: Compute maximum flow in a directed capacity network.

Input: capacities source sink

Output: max flow

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: simple network → flow value

Hint: Identify the invariant or transformation first; repeatedly BFS augmenting paths in residual graph.

Recommended approach: Repeatedly BFS augmenting paths in residual graph.

Complexity: O(VE²) time and O(V+E) space.

Solution explanation

Repeatedly BFS augmenting paths in residual graph. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(VE²) time and O(V+E) space.

236. Interval Tree Query

Difficulty: Advanced · Category: Trees

Problem statement: Build a balanced interval structure that returns overlaps with a query interval.

Input: intervals and query

Output: overlaps

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: [1,5],[8,9] query4,8 → both

Hint: Identify the invariant or transformation first; store subtree maximum endpoint and prune searches.

Recommended approach: Store subtree maximum endpoint and prune searches.

Complexity: O(log n + k) query typical and O(n) space.

Solution explanation

Store subtree maximum endpoint and prune searches. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log n + k) query typical and O(n) space.

237. AVL Tree

Difficulty: Advanced · Category: Trees

Problem statement: Implement a self-balancing binary search tree with rotations.

Input: insert/delete/search operations

Output: ordered tree

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: sorted inserts → balanced height

Hint: Identify the invariant or transformation first; track heights and rebalance four rotation cases.

Recommended approach: Track heights and rebalance four rotation cases.

Complexity: O(log n) operations and O(n) space.

Solution explanation

Track heights and rebalance four rotation cases. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log n) operations and O(n) space.

238. B Tree Search Model

Difficulty: Advanced · Category: Trees

Problem statement: Implement search and insertion for a small-degree B-tree.

Input: minimum degree and keys

Output: tree

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: insert many keys → multi-key nodes

Hint: Identify the invariant or transformation first; split full children before descent.

Recommended approach: Split full children before descent.

Complexity: O(log n) node visits and O(n) space.

Solution explanation

Split full children before descent. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log n) node visits and O(n) space.

239. Persistent Binary Tree Update

Difficulty: Advanced · Category: Persistent Data

Problem statement: Return a new tree after updating one key while sharing unchanged branches.

Input: immutable tree key value

Output: new tree

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: update leaf → siblings shared

Hint: Identify the invariant or transformation first; path-copy nodes from root to change.

Recommended approach: Path-copy nodes from root to change.

Complexity: O(h) time and O(h) new space.

Solution explanation

Path-copy nodes from root to change. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(h) time and O(h) new space.

240. Persistent Vector Trie Model

Difficulty: Advanced · Category: Persistent Data

Problem statement: Implement a simplified fixed-branching persistent indexed sequence.

Input: vector operations

Output: new vectors

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: get/set/push → structural sharing

Hint: Identify the invariant or transformation first; use bit-partitioned trie paths and tail buffer.

Recommended approach: Use bit-partitioned trie paths and tail buffer.

Complexity: O(log32 n) access/update and structural-sharing space.

Solution explanation

Use bit-partitioned trie paths and tail buffer. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log32 n) access/update and structural-sharing space.

241. LRU Cache with Doubly Linked List

Difficulty: Advanced · Category: Caching

Problem statement: Implement O(1) get and set with capacity eviction.

Input: capacity operations

Output: values

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: put a,b get a put c → b evicted

Hint: Identify the invariant or transformation first; map keys to linked nodes and move hits to front.

Recommended approach: Map keys to linked nodes and move hits to front.

Complexity: O(1) operations and O(capacity) space.

Solution explanation

Map keys to linked nodes and move hits to front. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) operations and O(capacity) space.

242. LFU Cache

Difficulty: Advanced · Category: Caching

Problem statement: Implement average O(1) least-frequently-used eviction with LRU tie-break.

Input: capacity operations

Output: values

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: frequency decides eviction

Hint: Identify the invariant or transformation first; map keys to nodes and frequencies to linked buckets.

Recommended approach: Map keys to nodes and frequencies to linked buckets.

Complexity: O(1) average operations and O(capacity) space.

Solution explanation

Map keys to nodes and frequencies to linked buckets. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average operations and O(capacity) space.

243. Count Min Sketch

Difficulty: Advanced · Category: Probabilistic Structures

Problem statement: Estimate stream frequencies with bounded memory and one-sided error.

Input: items width depth

Output: estimates

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: heavy key → approximate count

Hint: Identify the invariant or transformation first; hash into several counter rows and take minimum.

Recommended approach: Hash into several counter rows and take minimum.

Complexity: O(depth) update/query and O(width·depth) space.

Solution explanation

Hash into several counter rows and take minimum. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(depth) update/query and O(width·depth) space.

244. Bloom Filter

Difficulty: Advanced · Category: Probabilistic Structures

Problem statement: Implement membership with false positives but no false negatives before deletion.

Input: capacity hashes values

Output: maybe membership

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: added x → maybe true

Hint: Identify the invariant or transformation first; set multiple hashed bits and test all on lookup.

Recommended approach: Set multiple hashed bits and test all on lookup.

Complexity: O(k) per operation and O(m) bits.

Solution explanation

Set multiple hashed bits and test all on lookup. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(k) per operation and O(m) bits.

245. Consistent Hash Ring

Difficulty: Advanced · Category: Distributed Systems

Problem statement: Map keys to nodes while minimizing remapping when membership changes.

Input: nodes replicas keys

Output: assigned nodes

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: add node → subset moves

Hint: Identify the invariant or transformation first; hash virtual nodes on a sorted ring and binary search successors.

Recommended approach: Hash virtual nodes on a sorted ring and binary search successors.

Complexity: O(log N) lookup and O(N replicas) space.

Solution explanation

Hash virtual nodes on a sorted ring and binary search successors. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log N) lookup and O(N replicas) space.

246. Merkle Tree

Difficulty: Advanced · Category: Trees

Problem statement: Build a Merkle root and inclusion proof for ordered leaves.

Input: leaf byte strings

Output: root and proof

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: four leaves proof for index2 → verifies

Hint: Identify the invariant or transformation first; hash leaves then pair upward, carrying sibling hashes.

Recommended approach: Hash leaves then pair upward, carrying sibling hashes.

Complexity: O(n) build, O(log n) proof space.

Solution explanation

Hash leaves then pair upward, carrying sibling hashes. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) build, O(log n) proof space.

247. Rope String

Difficulty: Advanced · Category: Strings

Problem statement: Implement concatenation and slicing for very large strings using a balanced rope.

Input: string operations

Output: rope

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: string chunks concatenate → shared tree

Hint: Identify the invariant or transformation first; store lengths in tree nodes and rebalance.

Recommended approach: Store lengths in tree nodes and rebalance.

Complexity: O(log n) indexed operations typical and O(chunks) space.

Solution explanation

Store lengths in tree nodes and rebalance. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log n) indexed operations typical and O(chunks) space.

248. Unicode Grapheme Truncate

Difficulty: Advanced · Category: Internationalization

Problem statement: Truncate by user-perceived grapheme clusters with locale-aware segmentation.

Input: text max clusters

Output: text

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: family emoji plus text limit1 → full emoji

Hint: Identify the invariant or transformation first; use Intl.Segmenter and append whole segments.

Recommended approach: Use Intl.Segmenter and append whole segments.

Complexity: O(n) time and O(n) output space.

Solution explanation

Use Intl.Segmenter and append whole segments. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) time and O(n) output space.

249. Locale Sort Stable

Difficulty: Advanced · Category: Internationalization

Problem statement: Sort records by localized label then stable numeric ID.

Input: records locale options

Output: sorted records

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: ä,a under locale → collator order

Hint: Identify the invariant or transformation first; reuse one Intl.Collator comparator with deterministic tie-break.

Recommended approach: Reuse one Intl.Collator comparator with deterministic tie-break.

Complexity: O(n log n) time and O(n) space.

Solution explanation

Reuse one Intl.Collator comparator with deterministic tie-break. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n log n) time and O(n) space.

250. Temporal Recurring Schedule

Difficulty: Advanced · Category: Dates

Problem statement: Generate occurrences of a local-time weekly schedule across DST using Temporal or an adapter.

Input: zone local rule range

Output: instants

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: Sunday 09:00 → correct offsets

Hint: Identify the invariant or transformation first; represent zoned local intent and advance calendar units, not milliseconds.

Recommended approach: Represent zoned local intent and advance calendar units, not milliseconds.

Complexity: O(occurrences) time and space.

Solution explanation

Represent zoned local intent and advance calendar units, not milliseconds. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(occurrences) time and space.

251. Time Zone Availability Intersection

Difficulty: Advanced · Category: Dates

Problem statement: Find overlapping working intervals for participants in different zones.

Input: participant schedules range

Output: UTC overlaps

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: Karachi and London hours → overlap slots

Hint: Identify the invariant or transformation first; convert each local interval to instants then intersect sorted intervals.

Recommended approach: Convert each local interval to instants then intersect sorted intervals.

Complexity: O(n log n) time and O(n) space.

Solution explanation

Convert each local interval to instants then intersect sorted intervals. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n log n) time and O(n) space.

252. Regex ReDoS Analyzer Heuristic

Difficulty: Advanced · Category: Security

Problem statement: Flag suspicious nested quantifiers and ambiguous alternatives in a limited regex subset.

Input: pattern string

Output: findings

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: ^(a+)+$ → warning

Hint: Identify the invariant or transformation first; parse a bounded subset and inspect repetition over variable-length nodes.

Recommended approach: Parse a bounded subset and inspect repetition over variable-length nodes.

Complexity: O(pattern length) time and O(depth) space.

Solution explanation

Parse a bounded subset and inspect repetition over variable-length nodes. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(pattern length) time and O(depth) space.

253. Safe HTML Template Tag

Difficulty: Advanced · Category: Security

Problem statement: Create a tagged template that escapes interpolated text and explicitly marks reviewed safe fragments.

Input: template values

Output: trusted wrapper

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: user angle brackets → escaped

Hint: Identify the invariant or transformation first; escape text contexts and reject arbitrary raw fragments.

Recommended approach: Escape text contexts and reject arbitrary raw fragments.

Complexity: O(output length) time and space.

Solution explanation

Escape text contexts and reject arbitrary raw fragments. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(output length) time and space.

254. Content Security Policy Builder

Difficulty: Advanced · Category: Security

Problem statement: Build and validate a strict CSP from allowlisted directives and nonces.

Input: policy config

Output: header string

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: script nonce → script-src nonce token

Hint: Identify the invariant or transformation first; serialize known directives, quote keywords and reject injection characters.

Recommended approach: Serialize known directives, quote keywords and reject injection characters.

Complexity: O(entries) time and O(output) space.

Solution explanation

Serialize known directives, quote keywords and reject injection characters. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(entries) time and O(output) space.

255. PostMessage RPC

Difficulty: Advanced · Category: Security

Problem statement: Implement request-response messaging with origin validation, IDs, timeout and cancellation.

Input: Window ports methods

Output: Promise results

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: call sum → response 5

Hint: Identify the invariant or transformation first; validate origin/source/schema and correlate bounded pending requests.

Recommended approach: Validate origin/source/schema and correlate bounded pending requests.

Complexity: O(1) average routing and O(pending) space.

Solution explanation

Validate origin/source/schema and correlate bounded pending requests. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average routing and O(pending) space.

256. Capability Token Scope

Difficulty: Advanced · Category: Security

Problem statement: Model unforgeable in-memory capabilities using private objects and WeakMap metadata.

Input: issuer scopes

Output: callable capabilities

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: read token cannot write

Hint: Identify the invariant or transformation first; close over authority and validate capability identity via WeakMap.

Recommended approach: Close over authority and validate capability identity via WeakMap.

Complexity: O(1) checks and O(capabilities) metadata.

Solution explanation

Close over authority and validate capability identity via WeakMap. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) checks and O(capabilities) metadata.

257. Prototype Pollution Test Harness

Difficulty: Advanced · Category: Security

Problem statement: Fuzz merge/set-path functions with dangerous key combinations and verify prototypes remain unchanged.

Input: function under test

Output: findings

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: __proto__.polluted → blocked

Hint: Identify the invariant or transformation first; generate nested key cases and inspect fresh objects after each call.

Recommended approach: Generate nested key cases and inspect fresh objects after each call.

Complexity: O(cases·depth) time.

Solution explanation

Generate nested key cases and inspect fresh objects after each call. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(cases·depth) time.

258. Dependency Integrity Manifest

Difficulty: Advanced · Category: Supply Chain

Problem statement: Generate and verify hashes for a directory of static JavaScript assets.

Input: files

Output: manifest and verification

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: changed app.js → mismatch

Hint: Identify the invariant or transformation first; stream cryptographic hashes and compare exact normalized paths.

Recommended approach: Stream cryptographic hashes and compare exact normalized paths.

Complexity: O(total bytes) time and O(files) manifest space.

Solution explanation

Stream cryptographic hashes and compare exact normalized paths. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(total bytes) time and O(files) manifest space.

259. Schema Validator Compiler

Difficulty: Advanced · Category: Validation

Problem statement: Compile a small declarative schema into a reusable validator with path-aware issues.

Input: schema

Output: validator

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: number min0 against -1 → issue

Hint: Identify the invariant or transformation first; precompile node functions and avoid eval by composing closures.

Recommended approach: Precompile node functions and avoid eval by composing closures.

Complexity: O(schema) compile and O(value) validation.

Solution explanation

Precompile node functions and avoid eval by composing closures. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(schema) compile and O(value) validation.

260. JSON Schema Reference Resolver

Difficulty: Advanced · Category: Validation

Problem statement: Resolve local JSON Pointer references with cycle detection and caching.

Input: schema root

Output: resolved view or graph

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: $ref #/$defs/x → target

Hint: Identify the invariant or transformation first; parse pointer tokens, cache nodes and track active resolution stack.

Recommended approach: Parse pointer tokens, cache nodes and track active resolution stack.

Complexity: O(nodes+refs) time and O(nodes) space.

Solution explanation

Parse pointer tokens, cache nodes and track active resolution stack. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(nodes+refs) time and O(nodes) space.

261. Streaming Validator

Difficulty: Advanced · Category: Validation

Problem statement: Validate a stream of records with bounded concurrency and ordered issues.

Input: async records validators limit

Output: results

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: large JSONL → per-row results

Hint: Identify the invariant or transformation first; use a concurrency pool and sequence-indexed output buffer.

Recommended approach: Use a concurrency pool and sequence-indexed output buffer.

Complexity: O(n) work plus validator cost and O(limit) active space.

Solution explanation

Use a concurrency pool and sequence-indexed output buffer. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) work plus validator cost and O(limit) active space.

262. Expression Parser

Difficulty: Advanced · Category: Parsing

Problem statement: Tokenize and parse arithmetic expressions with precedence and parentheses into an AST.

Input: expression string

Output: AST

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: 2+3*4 → +(2,*(3,4))

Hint: Identify the invariant or transformation first; use Pratt parsing or precedence climbing.

Recommended approach: Use Pratt parsing or precedence climbing.

Complexity: O(n) time and O(n) space.

Solution explanation

Use Pratt parsing or precedence climbing. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) time and O(n) space.

263. Expression Evaluator

Difficulty: Advanced · Category: Parsing

Problem statement: Evaluate the arithmetic AST with an allowlisted environment and no eval.

Input: AST and variables

Output: number

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: x*2 with x3 → 6

Hint: Identify the invariant or transformation first; recursively dispatch on known node/operator kinds.

Recommended approach: Recursively dispatch on known node/operator kinds.

Complexity: O(nodes) time and O(depth) space.

Solution explanation

Recursively dispatch on known node/operator kinds. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(nodes) time and O(depth) space.

264. Mini Template Parser

Difficulty: Advanced · Category: Parsing

Problem statement: Parse text, escaped interpolation and conditional blocks into an AST.

Input: template string

Output: AST

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: Hello {{name}} → text plus interpolation

Hint: Identify the invariant or transformation first; use a scanner and stack for nested blocks.

Recommended approach: Use a scanner and stack for nested blocks.

Complexity: O(n) time and O(n) space.

Solution explanation

Use a scanner and stack for nested blocks. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) time and O(n) space.

265. Query Language Parser

Difficulty: Advanced · Category: Parsing

Problem statement: Parse filters such as status:open AND amount>100 into a validated AST.

Input: query text

Output: AST

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: status:open → comparison node

Hint: Identify the invariant or transformation first; tokenize, parse precedence and validate fields/operators.

Recommended approach: Tokenize, parse precedence and validate fields/operators.

Complexity: O(n) time and O(n) space.

Solution explanation

Tokenize, parse precedence and validate fields/operators. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) time and O(n) space.

266. Finite State Machine Compiler

Difficulty: Advanced · Category: State Machines

Problem statement: Compile a declarative transition table into a runtime with guards, actions and history.

Input: machine config

Output: interpreter

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: idle start → running

Hint: Identify the invariant or transformation first; validate graph then execute deterministic event selection.

Recommended approach: Validate graph then execute deterministic event selection.

Complexity: O(transitions) compile and O(candidates) per event.

Solution explanation

Validate graph then execute deterministic event selection. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(transitions) compile and O(candidates) per event.

267. Hierarchical State Machine

Difficulty: Advanced · Category: State Machines

Problem statement: Support nested states, inherited handlers and entry/exit actions.

Input: hierarchical config events

Output: states/effects

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: modal.open editing.save → transitions

Hint: Identify the invariant or transformation first; find least common ancestor and run exits then entries.

Recommended approach: Find least common ancestor and run exits then entries.

Complexity: O(depth) per transition and O(states) config space.

Solution explanation

Find least common ancestor and run exits then entries. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(depth) per transition and O(states) config space.

268. Saga Compensation Runner

Difficulty: Advanced · Category: Workflows

Problem statement: Execute steps and reverse completed compensations after failure.

Input: steps with execute/compensate

Output: result

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: reserve succeeds charge fails → release reserve

Hint: Identify the invariant or transformation first; record completed steps and compensate in reverse with aggregated errors.

Recommended approach: Record completed steps and compensate in reverse with aggregated errors.

Complexity: O(steps) time plus I/O and O(steps) state.

Solution explanation

Record completed steps and compensate in reverse with aggregated errors. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(steps) time plus I/O and O(steps) state.

269. Durable Workflow Replay

Difficulty: Advanced · Category: Workflows

Problem statement: Rebuild workflow state by replaying deterministic event history.

Input: events reducer

Output: current state

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: started,completed → done

Hint: Identify the invariant or transformation first; keep reducer pure, version events and snapshot periodically.

Recommended approach: Keep reducer pure, version events and snapshot periodically.

Complexity: O(events) replay and O(state) space.

Solution explanation

Keep reducer pure, version events and snapshot periodically. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(events) replay and O(state) space.

270. Event Sourcing Projection

Difficulty: Advanced · Category: Architecture

Problem statement: Build idempotent read-model projections from ordered events with checkpoints.

Input: event stream projection

Output: read model

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: order events → order summary

Hint: Identify the invariant or transformation first; apply by event ID/version and persist checkpoint transactionally.

Recommended approach: Apply by event ID/version and persist checkpoint transactionally.

Complexity: O(events) time and O(model) space.

Solution explanation

Apply by event ID/version and persist checkpoint transactionally. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(events) time and O(model) space.

271. CQRS Command Bus

Difficulty: Advanced · Category: Architecture

Problem statement: Route validated commands to handlers and publish resulting events without hidden globals.

Input: commands registry

Output: results/events

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: CreateOrder → OrderCreated

Hint: Identify the invariant or transformation first; use explicit registry, middleware and unit-of-work boundary.

Recommended approach: Use explicit registry, middleware and unit-of-work boundary.

Complexity: O(1) average dispatch and O(handlers) space.

Solution explanation

Use explicit registry, middleware and unit-of-work boundary. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average dispatch and O(handlers) space.

272. Dependency Injection Container

Difficulty: Advanced · Category: Architecture

Problem statement: Build a scoped DI container with cycle detection and disposal.

Input: provider definitions scope

Output: resolved services

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: A depends B → constructed order

Hint: Identify the invariant or transformation first; dFS resolution stack, cache by scope and dispose reverse order.

Recommended approach: DFS resolution stack, cache by scope and dispose reverse order.

Complexity: O(V+E) resolution and O(V) space.

Solution explanation

DFS resolution stack, cache by scope and dispose reverse order. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(V+E) resolution and O(V) space.

273. Plugin Host

Difficulty: Advanced · Category: Architecture

Problem statement: Load versioned plugins with capability-scoped APIs, lifecycle and isolation boundaries.

Input: plugin manifests

Output: activated plugins

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: compatible plugin → start then stop

Hint: Identify the invariant or transformation first; validate manifest, negotiate version and expose minimal host capabilities.

Recommended approach: Validate manifest, negotiate version and expose minimal host capabilities.

Complexity: O(plugins) lifecycle plus plugin work.

Solution explanation

Validate manifest, negotiate version and expose minimal host capabilities. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(plugins) lifecycle plus plugin work.

274. Module Boundary Analyzer

Difficulty: Advanced · Category: Tooling

Problem statement: Parse import graphs and report forbidden cross-feature dependencies and cycles.

Input: source files rules

Output: violations

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: feature A imports B/private → violation

Hint: Identify the invariant or transformation first; extract static imports, normalize paths and analyze graph.

Recommended approach: Extract static imports, normalize paths and analyze graph.

Complexity: O(files+imports) time and space.

Solution explanation

Extract static imports, normalize paths and analyze graph. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(files+imports) time and space.

275. Tree Shaking Side Effect Audit

Difficulty: Advanced · Category: Tooling

Problem statement: Identify modules whose top-level behavior makes side-effect-free metadata unsafe.

Input: module graph

Output: findings

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: top-level register call → side effect

Hint: Identify the invariant or transformation first; parse AST and classify top-level writes/calls conservatively.

Recommended approach: Parse AST and classify top-level writes/calls conservatively.

Complexity: O(source size) time and AST space.

Solution explanation

Parse AST and classify top-level writes/calls conservatively. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(source size) time and AST space.

276. Source Map Position Mapper

Difficulty: Advanced · Category: Tooling

Problem statement: Map generated line-column positions to original sources using decoded mappings.

Input: source map and generated position

Output: original location

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: bundle 10:5 → src/app.js 3:2

Hint: Identify the invariant or transformation first; decode VLQ segments and binary search generated positions.

Recommended approach: Decode VLQ segments and binary search generated positions.

Complexity: O(map size) build and O(log segments) query.

Solution explanation

Decode VLQ segments and binary search generated positions. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(map size) build and O(log segments) query.

277. Static Dead Export Finder

Difficulty: Advanced · Category: Tooling

Problem statement: Report exports not reachable from configured entry points while respecting dynamic boundaries.

Input: module graph entries

Output: unused exports

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: unused helper → finding

Hint: Identify the invariant or transformation first; build symbol-level reachability with conservative dynamic-import rules.

Recommended approach: Build symbol-level reachability with conservative dynamic-import rules.

Complexity: O(symbols+edges) time and space.

Solution explanation

Build symbol-level reachability with conservative dynamic-import rules. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(symbols+edges) time and space.

278. Property Based Test Generator

Difficulty: Advanced · Category: Testing

Problem statement: Generate constrained random values, shrink failures and report reproducible seeds.

Input: arbitrary property runs

Output: result

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: failing array shrinks to minimal case

Hint: Identify the invariant or transformation first; separate generation, predicate execution and structural shrinking.

Recommended approach: Separate generation, predicate execution and structural shrinking.

Complexity: O(runs·test cost plus shrinking) time.

Solution explanation

Separate generation, predicate execution and structural shrinking. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(runs·test cost plus shrinking) time.

279. Mutation Testing Core

Difficulty: Advanced · Category: Testing

Problem statement: Apply simple source mutations and report which survive the test suite.

Input: source tests mutation set

Output: report

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: replace > with >= survives → weakness

Hint: Identify the invariant or transformation first; transform AST one mutation at a time and run isolated tests.

Recommended approach: Transform AST one mutation at a time and run isolated tests.

Complexity: O(mutations·test suite) time.

Solution explanation

Transform AST one mutation at a time and run isolated tests. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(mutations·test suite) time.

280. Deterministic Fake Clock

Difficulty: Advanced · Category: Testing

Problem statement: Implement injectable wall and monotonic clocks with timers advanced by tests.

Input: scheduled callbacks and advance

Output: execution

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: timer 10 advance10 → callback

Hint: Identify the invariant or transformation first; use a min heap ordered by due time and stable sequence.

Recommended approach: Use a min heap ordered by due time and stable sequence.

Complexity: O(log n) schedule and O(k log n) advance.

Solution explanation

Use a min heap ordered by due time and stable sequence. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log n) schedule and O(k log n) advance.

281. Network Fault Simulator

Difficulty: Advanced · Category: Testing

Problem statement: Wrap fetch to inject latency, timeout, reset, malformed data and status sequences deterministically.

Input: scenario request

Output: simulated response/error

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: first 500 then 200 → retry test

Hint: Identify the invariant or transformation first; match requests to scripted outcomes with fake clock and AbortSignal.

Recommended approach: Match requests to scripted outcomes with fake clock and AbortSignal.

Complexity: O(1) average scenario step.

Solution explanation

Match requests to scripted outcomes with fake clock and AbortSignal. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(1) average scenario step.

282. Model Based State Test

Difficulty: Advanced · Category: Testing

Problem statement: Generate action sequences against a model and implementation and compare observable state.

Input: model commands implementation

Output: counterexample

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: random cart actions → invariant checks

Hint: Identify the invariant or transformation first; define preconditions, apply both systems and shrink failing sequence.

Recommended approach: Define preconditions, apply both systems and shrink failing sequence.

Complexity: O(sequences·steps) time.

Solution explanation

Define preconditions, apply both systems and shrink failing sequence. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(sequences·steps) time.

283. Async Leak Detector

Difficulty: Advanced · Category: Testing

Problem statement: Detect unfinished timers, listeners and Promises owned by a test scope.

Input: instrumented scope

Output: leak report

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: test ends with interval → finding

Hint: Identify the invariant or transformation first; wrap resource creation and require explicit disposal/settlement.

Recommended approach: Wrap resource creation and require explicit disposal/settlement.

Complexity: O(resources) tracking and report space.

Solution explanation

Wrap resource creation and require explicit disposal/settlement. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(resources) tracking and report space.

284. Structured Logger

Difficulty: Advanced · Category: Observability

Problem statement: Build a logger with levels, context propagation, redaction, sampling and JSON output.

Input: event context

Output: log record

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: request error → correlated JSON

Hint: Identify the invariant or transformation first; merge immutable context, redact schema paths and serialize safely.

Recommended approach: Merge immutable context, redact schema paths and serialize safely.

Complexity: O(record size) time and space.

Solution explanation

Merge immutable context, redact schema paths and serialize safely. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(record size) time and space.

285. Trace Context Propagation

Difficulty: Advanced · Category: Observability

Problem statement: Propagate trace/span context through async operations without global mutation leakage.

Input: operation tree

Output: correlated spans

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: HTTP to DB → parent child spans

Hint: Identify the invariant or transformation first; use runtime async context where available or explicit context parameters.

Recommended approach: Use runtime async context where available or explicit context parameters.

Complexity: O(spans) time and space.

Solution explanation

Use runtime async context where available or explicit context parameters. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(spans) time and space.

286. Metrics Histogram

Difficulty: Advanced · Category: Observability

Problem statement: Implement fixed-bucket latency histogram with count, sum and quantile approximation.

Input: observations buckets

Output: snapshot

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: latencies → bucket counts

Hint: Identify the invariant or transformation first; binary search bucket, increment counters and expose cumulative snapshot.

Recommended approach: Binary search bucket, increment counters and expose cumulative snapshot.

Complexity: O(log buckets) update and O(buckets) space.

Solution explanation

Binary search bucket, increment counters and expose cumulative snapshot. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(log buckets) update and O(buckets) space.

287. Error Fingerprinting

Difficulty: Advanced · Category: Observability

Problem statement: Group similar errors using normalized stack, type and stable context while excluding secrets.

Input: error records

Output: fingerprint

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: same root stack diff IDs → same group

Hint: Identify the invariant or transformation first; normalize volatile tokens and hash selected fields.

Recommended approach: Normalize volatile tokens and hash selected fields.

Complexity: O(record size) time and O(groups) space.

Solution explanation

Normalize volatile tokens and hash selected fields. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(record size) time and O(groups) space.

288. Memory Leak Reproducer

Difficulty: Advanced · Category: Debugging

Problem statement: Build a deterministic harness that exposes listener or detached-DOM retention over iterations.

Input: setup action teardown iterations

Output: heap evidence

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: 100 modal opens → retained nodes

Hint: Identify the invariant or transformation first; run repeatable lifecycle, force diagnostic GC where allowed and inspect retaining paths.

Recommended approach: Run repeatable lifecycle, force diagnostic GC where allowed and inspect retaining paths.

Complexity: O(iterations) scenario work.

Solution explanation

Run repeatable lifecycle, force diagnostic GC where allowed and inspect retaining paths. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(iterations) scenario work.

289. Event Loop Lag Monitor

Difficulty: Advanced · Category: Performance

Problem statement: Measure event-loop delay distribution without creating excessive overhead.

Input: sampling interval window

Output: lag metrics

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: blocked 200ms → lag spike

Hint: Identify the invariant or transformation first; schedule recurring monotonic timer and record drift in histogram.

Recommended approach: Schedule recurring monotonic timer and record drift in histogram.

Complexity: O(samples) time and bounded histogram space.

Solution explanation

Schedule recurring monotonic timer and record drift in histogram. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(samples) time and bounded histogram space.

290. Adaptive Batch Processor

Difficulty: Advanced · Category: Performance

Problem statement: Choose batch size to meet a target main-thread time slice while processing all items.

Input: items targetMs worker

Output: completion

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: large list → responsive chunks

Hint: Identify the invariant or transformation first; measure batches, adjust size and yield to host tasks.

Recommended approach: Measure batches, adjust size and yield to host tasks.

Complexity: O(n) work and O(batch) active space.

Solution explanation

Measure batches, adjust size and yield to host tasks. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) work and O(batch) active space.

291. DOM Layout Thrash Detector

Difficulty: Advanced · Category: Performance

Problem statement: Instrument selected layout reads/writes and report alternating patterns in one task.

Input: instrumented operations

Output: findings

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: write-read-write → warning

Hint: Identify the invariant or transformation first; record operation sequence and group by event-loop turn.

Recommended approach: Record operation sequence and group by event-loop turn.

Complexity: O(operations) time and space.

Solution explanation

Record operation sequence and group by event-loop turn. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(operations) time and space.

292. Bundle Budget Checker

Difficulty: Advanced · Category: Performance

Problem statement: Compare built asset sizes and module contributions with committed budgets.

Input: manifest budgets

Output: pass or findings

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: main.js exceeds gzip budget → fail

Hint: Identify the invariant or transformation first; normalize assets, compute compressed sizes and diff baseline.

Recommended approach: Normalize assets, compute compressed sizes and diff baseline.

Complexity: O(total bytes) hashing/compression time.

Solution explanation

Normalize assets, compute compressed sizes and diff baseline. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(total bytes) hashing/compression time.

293. Memoization Cost Model

Difficulty: Advanced · Category: Performance

Problem statement: Estimate whether memoization wins from hit rate, compute cost, lookup cost and memory budget.

Input: measurements

Output: recommendation

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: low hit cheap function → do not cache

Hint: Identify the invariant or transformation first; calculate expected cost and validate with benchmark.

Recommended approach: Calculate expected cost and validate with benchmark.

Complexity: O(samples) measurement and O(1) model.

Solution explanation

Calculate expected cost and validate with benchmark. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(samples) measurement and O(1) model.

294. External Merge Sort

Difficulty: Advanced · Category: Algorithms

Problem statement: Sort data larger than memory using sorted runs and k-way merge.

Input: record stream memory budget

Output: sorted stream

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: huge file → ordered output

Hint: Identify the invariant or transformation first; create bounded sorted runs then heap-merge them.

Recommended approach: Create bounded sorted runs then heap-merge them.

Complexity: O(n log n) time and O(memory plus runs) storage.

Solution explanation

Create bounded sorted runs then heap-merge them. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n log n) time and O(memory plus runs) storage.

295. Reservoir Sampling

Difficulty: Advanced · Category: Algorithms

Problem statement: Select k uniform samples from a stream of unknown length.

Input: item stream and k

Output: sample

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: large stream k10 → uniform reservoir

Hint: Identify the invariant or transformation first; fill reservoir then replace with decreasing probability.

Recommended approach: Fill reservoir then replace with decreasing probability.

Complexity: O(n) time and O(k) space.

Solution explanation

Fill reservoir then replace with decreasing probability. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) time and O(k) space.

296. HyperLogLog Model

Difficulty: Advanced · Category: Probabilistic Structures

Problem statement: Estimate distinct count with fixed memory using hashed leading-zero ranks.

Input: items precision

Output: estimate

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: millions IDs → approximate cardinality

Hint: Identify the invariant or transformation first; update registers by bucket and rank then apply bias correction model.

Recommended approach: Update registers by bucket and rank then apply bias correction model.

Complexity: O(n) time and O(2^p) space.

Solution explanation

Update registers by bucket and rank then apply bias correction model. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n) time and O(2^p) space.

297. Rolling Hash Substring Search

Difficulty: Advanced · Category: Strings

Problem statement: Find pattern occurrences with a rolling hash and verify collisions.

Input: text pattern

Output: indices

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: abracadabra,abra → [0,7]

Hint: Identify the invariant or transformation first; compute window hash updates and compare text on hash match.

Recommended approach: Compute window hash updates and compare text on hash match.

Complexity: Average O(n+m) time and O(1) space.

Solution explanation

Compute window hash updates and compare text on hash match. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match Average O(n+m) time and O(1) space.

298. Suffix Array Basic

Difficulty: Advanced · Category: Strings

Problem statement: Build a suffix array and search substring occurrences.

Input: text and queries

Output: positions

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: banana,ana → [1,3]

Hint: Identify the invariant or transformation first; sort suffix ranks by doubling then binary search query range.

Recommended approach: Sort suffix ranks by doubling then binary search query range.

Complexity: O(n log² n) simple build and O(n) space.

Solution explanation

Sort suffix ranks by doubling then binary search query range. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(n log² n) simple build and O(n) space.

299. Aho Corasick Multi Pattern

Difficulty: Advanced · Category: Tries

Problem statement: Find all occurrences of many patterns in one text scan.

Input: patterns text

Output: matches

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: he,she in she → both matches

Hint: Identify the invariant or transformation first; build trie failure links and output links.

Recommended approach: Build trie failure links and output links.

Complexity: O(total patterns + text + matches) time.

Solution explanation

Build trie failure links and output links. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match O(total patterns + text + matches) time.

300. Levenshtein Search BK Tree

Difficulty: Advanced · Category: Trees

Problem statement: Index words for approximate edit-distance queries.

Input: dictionary query maxDistance

Output: words

Constraints: Define failure, cancellation and ownership semantics; keep resources bounded; and justify correctness for production-scale or adversarial input.

Example: book query boak d1 → book

Hint: Identify the invariant or transformation first; build BK-tree edges by distance and prune query ranges.

Recommended approach: Build BK-tree edges by distance and prune query ranges.

Complexity: Query depends on metric distribution and O(words) space.

Solution explanation

Build BK-tree edges by distance and prune query ranges. Validate the documented boundary cases before the main operation, preserve the required output shape, and add tests for the example plus empty, minimum, maximum and invalid inputs. The implementation is complete when its observed time and space costs match Query depends on metric distribution and O(words) space.