messages
listlengths
2
634
[ { "role": "user", "content": "Implement Dijkstra's shortest path in Python (stdlib only) as a package: dijkstra/graph.py with `shortest_paths(adj: dict[str, list[tuple[str, float]]], src: str) -> dict[str, float]` using heapq, and dijkstra/cli.py that reads an edge list file (lines: \"u v weight\") plus a s...
[ { "role": "user", "content": "In TypeScript, implement topological sort with useful cycle diagnostics. Set up a minimal npm project (package.json, tsconfig.json, vitest). src/toposort.ts exports `toposort(edges: [string, string][]): { order: string[] } | { cycle: string[] }` — Kahn's algorithm; when a cycle...
[ { "role": "user", "content": "Build a max-flow module in Python: dinic.py with a Dinic's algorithm implementation (BFS level graph + DFS blocking flow, adjacency via edge arrays with reverse-edge indices). Deliverables: `class Dinic` with add_edge(u, v, cap) and max_flow(s, t); a `bipartite_matching(left, r...
[ { "role": "user", "content": "Write tarjan.py implementing Tarjan's strongly connected components algorithm iteratively (no recursion, so it survives a 50k-node path graph without hitting Python's recursion limit). API: `scc(adj: dict[int, list[int]]) -> list[list[int]]` returning components in reverse topo...
[ { "role": "user", "content": "Kruskal MST with a proper disjoint-set union. Write mst.py: DSU class (path compression + union by size), and `minimum_spanning_forest(n, edges)` where edges are (w, u, v), returning (total_weight, chosen_edges). Handle disconnected graphs (forest, not error). Then verify it th...
[ { "role": "user", "content": "Bellman-Ford that doesn't just say \"negative cycle: yes\" — it must return an actual cycle. Python file bellman_ford.py: `shortest_paths(n, edges, src)` returns dist list, and if a negative cycle is reachable from src, raise NegativeCycleError carrying `.cycle`, a list of vert...
[ { "role": "user", "content": "Implement A* pathfinding on a 2D grid in Python and prove the heuristic matters. astar.py: grid given as list of strings ('.' free, '#' wall), 4-directional moves, Manhattan heuristic; `astar(grid, start, goal)` returns (path, expanded_count) where path is the list of cells, an...
[ { "role": "user", "content": "Write bridges.py finding all bridges and articulation points of an undirected graph in one DFS pass (iterative, low-link). API: `bridges_and_cut_vertices(n, edges) -> (set_of_bridges, set_of_cut_vertices)` with bridges as frozenset pairs. Verify with two layers of tests: hand-b...
[ { "role": "user", "content": "Quick one: word-ladder shortest transformation with BFS. Python script ladder.py containing WORDS = [\"cold\",\"cord\",\"card\",\"ward\",\"warm\",\"wart\",\"what\",\"cart\",\"hard\",\"lard\",\"lord\",\"word\",\"wood\",\"good\",\"gold\"] and `ladder(start, end, words)` returning...
[ { "role": "user", "content": "Node.js task, plain JavaScript with the built-in node:test runner. Implement Hierholzer's algorithm in eulerian.js: `eulerianCircuit(edges)` for an undirected multigraph given as [u,v] pairs, returning a vertex sequence using every edge exactly once, or null when no circuit exi...
[ { "role": "user", "content": "Hopcroft-Karp maximum bipartite matching in Python. hopcroft_karp.py: `max_matching(n_left, n_right, adj: list[list[int]]) -> tuple[int, list[int]]` (size, and match_of_left with -1 for unmatched), using the BFS layering + DFS augmenting phases characteristic of the algorithm —...
[ { "role": "user", "content": "Implement 0-1 BFS on a weighted grid. Python zero_one_bfs.py: the map is a list of strings where '.' costs 0 to step onto and '~' costs 1, '#' is impassable; `min_cost(grid, start, goal)` uses a collections.deque (appendleft for 0-edges, append for 1-edges) — no heapq allowed, ...
[ { "role": "user", "content": "Build a correct AVL-tree-backed sorted map in Python, stdlib only. avl.py: class AVLMap with insert(key, value), get(key), delete(key), min_key(), max_key(), and in-order items(); rebalance with all four rotation cases; maintain height fields. Crucially include `_check_invarian...
[ { "role": "user", "content": "Fenwick tree, both flavors, one file. fenwick.py in Python: class Fenwick (point update, prefix sum, plus range_sum(l, r) and a kth-smallest style `find_kth(k)` that walks the tree in O(log n) assuming all values are non-negative counts), and class RangeAddFenwick (range add, p...
[ { "role": "user", "content": "Segment tree with lazy propagation, and I want it fuzzed hard. Python segtree.py: iterative or recursive tree supporting range assign (set every element in [l, r) to v), range add, and range min query, with correct lazy composition (assign overrides pending add; add after assig...
[ { "role": "user", "content": "Lowest common ancestor via binary lifting. Python lca.py: build from a rooted tree given as parent array (parent[root] == -1); precompute up[k][v] jump tables and depth; `lca(u, v)` in O(log n), plus `dist(u, v)` in edges. Tests (pytest): a hand-drawn 12-node tree with a dozen ...
[ { "role": "user", "content": "Implement a treap (randomized balanced BST) as an ordered multiset in Python. treap.py: split/merge based implementation with insert(x), erase_one(x), count_less(x), kth_smallest(k) (1-indexed), and len support. Seed the priority RNG per-instance for reproducibility. Pytest sui...
[ { "role": "user", "content": "TypeScript binary search tree with a lazy in-order iterator. Project: package.json + tsconfig + vitest. src/bst.ts exports class BST<T> with a comparator constructor arg, insert, has, delete, size, and [Symbol.iterator]() implemented as a generator doing iterative in-order trav...
[ { "role": "user", "content": "Expert task: a persistent (fully immutable) sorted map in Python with structural sharing, in a package persistent_map/. Use a weight-balanced tree: every insert/delete returns a NEW map object; old versions stay valid forever. API: PMap.empty(), m2 = m1.set(k, v), m3 = m2.delet...
[ { "role": "user", "content": "Merkle tree over file chunks, Python stdlib only (hashlib). merkle.py: chunk a file into 4 KiB blocks, build a binary Merkle tree with sha256 (duplicate last node when a level is odd), expose root_hash(path), `proof(path, chunk_index)` returning the sibling-hash audit path, and...
[ { "role": "user", "content": "Write an indexed binary min-heap with decrease-key in Python — the piece heapq is missing. iheap.py: class IndexedHeap keyed by item id, with push(id, priority), pop() returning (id, priority), decrease_key(id, new_priority) in O(log n) via a position map, contains, and len. Ra...
[ { "role": "user", "content": "K-way merge two ways, then race them. Python kmerge.py: `merge_heap(iterators)` merging k sorted iterators lazily with heapq (tie-break stable by iterator index, never materializing inputs), and `merge_naive(lists)` that concatenates and sorts. Correctness pytest: equal output ...
[ { "role": "user", "content": "Running-median structure with two heaps in Python, under 60 lines for the class. median.py: class RunningMedian with add(x) and median() (average of middles for even counts), max-heap via negation on the low side, min-heap on the high side, rebalanced so sizes differ by at most...
[ { "role": "user", "content": "Benchmark d-ary heaps properly. Python daryheap.py: class DHeap(d) supporting push/pop for d>=2, array-based, sift routines written once for arbitrary d. Correctness first: pytest fuzz vs heapq on 5000 seeded ops for d in (2, 3, 4, 8); heapsort of 10000 seeded ints equals sorte...
[ { "role": "user", "content": "JavaScript priority queue with pluggable comparator, tested with node:test. pq.js exports class PriorityQueue accepting (a, b) => number; methods push, pop, peek, size; binary heap internals. Then use it: `mergeSorted(arrays)` merging k sorted arrays via the queue. Tests (pq.te...
[ { "role": "user", "content": "Autocomplete engine on a trie, Python stdlib only. trie_complete.py: class Autocomplete built from (word, weight) pairs; `top(prefix, k)` returns the k highest-weight completions (ties broken alphabetically) by collecting the prefix subtree and heapq.nsmallest on (-weight, word...
[ { "role": "user", "content": "Aho-Corasick multi-pattern string search in Python. aho.py: build trie + BFS failure links + output links; `find_all(text, patterns)` yields (start_index, pattern) for every occurrence including overlapping ones and patterns that are substrings of other patterns. Verify against...
[ { "role": "user", "content": "Compressed radix tree (Patricia trie) for byte strings in Python. radix.py: class RadixSet with add(key: bytes), contains, discard, and `keys_with_prefix(prefix)` returning sorted results; edges hold byte-string fragments that split on divergence and re-merge on removal (a node...
[ { "role": "user", "content": "Max-XOR pair via a bitwise trie. Python xor_trie.py: `max_xor_pair(nums: list[int]) -> tuple[int, int, int]` returning (best_xor, a, b) for 32-bit non-negative ints — insert each number into a 0/1 trie MSB-first, and for each number greedily walk toward the opposite bit. Handle...
[ { "role": "user", "content": "Edit distance that shows its work. Python edit_distance.py: `distance(a, b)` (Levenshtein, unit costs) and `script(a, b)` returning an edit script as a list of operations like (\"keep\",\"c\"), (\"sub\",\"a\",\"b\"), (\"ins\",\"x\"), (\"del\",\"y\") recovered by tracebacking th...
[ { "role": "user", "content": "0/1 knapsack with reconstruction, Python. knapsack.py: `solve(capacity, items)` where items are (name, weight, value), returning (best_value, chosen_names) via DP over capacity plus a parent traceback. Constraints: O(n*capacity) time, and the chosen set must actually achieve be...
[ { "role": "user", "content": "Longest increasing subsequence in O(n log n) with actual sequence recovery — patience sorting with parent pointers, not just the length. Python lis.py: `lis(seq) -> list` returning one longest strictly-increasing subsequence. Verify three ways in pytest: (1) result is strictly ...
[ { "role": "user", "content": "Held-Karp bitmask TSP in Python. tsp.py: `tsp(dist: list[list[float]]) -> tuple[float, list[int]]` returning optimal tour cost and the vertex order (cycle starting at 0), DP over subsets with bitmasks and a parent table for path recovery. Tests: exact answers vs itertools.permu...
[ { "role": "user", "content": "Small but complete: coin change with reconstruction. Python coins.py: `min_coins(target, denoms)` returns (count, multiset_of_coins) or None when unreachable. Include the classic greedy-breaking case in tests: denoms [1, 15, 25] target 30 must give [15, 15], not [25, 1, 1, 1, 1...
[ { "role": "user", "content": "Weighted interval scheduling, Python. wis.py: jobs are (start, end, weight) with end exclusive; `best_schedule(jobs)` returns (total_weight, chosen_jobs) — sort by end, binary search (bisect) for the latest compatible predecessor, DP with traceback. Assertions that matter: chos...
[ { "role": "user", "content": "Digit DP exercise, Python. digit_dp.py: `count(a, b, k)` = how many integers in [a, b] have digit sum divisible by k, implemented as a memoized digit DP over the decimal representation with a tight-bound flag (no iterating the range). Brute-force cross-check for every (a, b, k)...
[ { "role": "user", "content": "In TypeScript: longest common subsequence powering a word-level diff. Vitest project. src/lcs.ts: `lcs<T>(a: T[], b: T[], eq?)` returning the subsequence via DP with O(min) space for the length but full traceback for the sequence (two-pass or Hirschberg — your choice, say which...
[ { "role": "user", "content": "Matrix chain multiplication in Python with proof-by-evaluation. matrix_chain.py: `best_order(dims)` for matrices A_i of dims[i] x dims[i+1], returning (min_scalar_mults, parenthesization_string) like \"((A0 A1) A2)\" via interval DP + split table. Tests must not trust the DP: i...
[ { "role": "user", "content": "Build a regex-lite matcher with DP and pit it against Python's re module. rmatch.py: `match(pattern, s) -> bool` supporting literals, '.', and '*' (zero-or-more of the previous atom), full-string semantics. Implement it bottom-up (no recursion) over a (pattern_pos, string_pos) ...
[ { "role": "user", "content": "KMP, fuzz-proofed. Python kmp.py: `prefix_function(p)` and `find_all(text, pattern)` returning every occurrence index including overlapping ones. Cross-check against an oracle built on str.find in a loop for 1000 seeded random (text, pattern) pairs over alphabet \"ab\" (that al...
[ { "role": "user", "content": "Z-algorithm in Python with a naive oracle. z_algorithm.py: `z_array(s)` (z[0] = len(s)) and `search(text, pattern)` via the concatenation-with-sentinel trick. Pytest: z_array matches a quadratic reference (character-by-character extension) on 1000 seeded random strings over \"a...
[ { "role": "user", "content": "Suffix array + LCP in Python, no external libraries. suffix.py: `suffix_array(s)` via prefix-doubling with radix or key-sort per round (O(n log^2 n) is fine, document it), `lcp_array(s, sa)` via Kasai, and `longest_repeated_substring(s)` reading the LCP max. Tests: brute-force ...
[ { "role": "user", "content": "Manacher's algorithm, verified against expand-around-center. Python manacher.py: `longest_palindrome(s)` returning the leftmost longest palindromic substring in O(n) using the transformed string with separators; also expose `palindrome_radii(s)` for testing. Pytest: agreement w...
[ { "role": "user", "content": "Build a Burrows-Wheeler compression pipeline CLI in Python, stdlib only. Package bwt_tool/ with bwt.py (transform via sorted rotations using a sentinel byte 0x00, and inverse via the LF-mapping/first-column trick — no storing all rotations for the inverse), mtf.py (move-to-fron...
[ { "role": "user", "content": "Rabin-Karp done honestly, including the collision story. Python rabin_karp.py: `find_all(text, pattern)` single-pattern rolling hash (polynomial hash mod a large prime, verify candidates by direct comparison), and `find_any(text, patterns)` for a set of same-length patterns usi...
[ { "role": "user", "content": "Quick JavaScript exercise with node:test. rle.js: `encode(s)` and `decode(s)` for run-length encoding with digit escaping — runs become \"<count><char>\" only when count >= 2, single chars pass through, and literal digits in the input are escaped with a backslash so decode is u...
[ { "role": "user", "content": "Implement Myers' O(ND) diff in Python and prove patches apply. myers.py: `diff(a: list[str], b: list[str])` using the greedy furthest-reaching D-path algorithm (the real thing with the V array and trace-back through saved V snapshots — not difflib), emitting (\"equal\", line) /...
[ { "role": "user", "content": "Convex hull via Andrew's monotone chain, Python, exact integer arithmetic. hull.py: `convex_hull(points)` on int lattice points, returning the hull counter-clockwise starting from the lowest-then-leftmost point, EXCLUDING collinear interior boundary points. Tests with pytest + ...
[ { "role": "user", "content": "Expert geometry task: a working Bentley-Ottmann sweep line in Python reporting all intersection points among n segments. Package sweep/ with geometry.py (exact orientation and segment-intersection predicates using integer cross products; intersection points as fractions.Fractio...
[ { "role": "user", "content": "Closest pair of points, divide and conquer, Python. closest_pair.py: `closest_pair(points)` returning (d, (p, q)) in O(n log n) with the sorted-by-y merge and the 7-neighbor strip check. Tests: exact agreement with O(n^2) brute force on 400 seeded random sets (sizes 2-120, both...
[ { "role": "user", "content": "Point-in-polygon that survives the boundary. Python pip.py: `classify(point, polygon)` returning \"inside\", \"outside\", or \"boundary\" for simple polygons with integer vertices — use exact integer arithmetic: on-segment checks for the boundary answer, then a ray-casting pari...
[ { "role": "user", "content": "Shoelace utilities, quick. Python polygon.py: `area(poly)`, `centroid(poly)`, `is_clockwise(poly)` via the signed shoelace sum, working for any simple polygon vertex order. Tests: unit square (area 1, centroid (0.5, 0.5)), a triangle with known centroid, an L-shaped hexagon com...
[ { "role": "user", "content": "Rotating calipers for point-set diameter in Python. calipers.py: `diameter(points)` — build the convex hull (monotone chain, include it in the file), then rotate antipodal pairs to find the farthest pair, returning (dist_squared, pair) in exact integer arithmetic (never take a ...
[ { "role": "user", "content": "Merge overlapping intervals — small task, exact semantics. Python intervals.py: `merge(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]` treating intervals as closed, so touching intervals like (1, 3) and (3, 5) DO merge; input in any order; output sorted and disjoint...
[ { "role": "user", "content": "Calendar double-booking guard, Python. calendar_book.py: class Calendar with `book(start, end) -> bool` (half-open [start, end)) that accepts iff the new event overlaps nothing, keeping events in a sorted list via the bisect module for O(log n) lookup + O(n) insert; and `booked...
[ { "role": "user", "content": "Meeting rooms via sweep line, Python. rooms.py: `min_rooms(meetings)` returning the minimum number of rooms for half-open intervals, and `peak_load(meetings)` returning (max_concurrent, a_time_at_which_it_occurs) — both from one sorted boundary sweep (+1 at start, -1 at end; en...
[ { "role": "user", "content": "Augmented interval tree in Python — beat the linear scan and prove it. itree.py: a balanced-enough interval tree (red-black is overkill; build a static tree from sorted input, or a treap keyed by low endpoint, your call — say which) storing closed intervals, with `stab(x)` retu...
[ { "role": "user", "content": "TypeScript CIDR toolkit built on interval math. Vitest project. src/cidr.ts: `cidrToRange(\"10.0.0.0/24\")` returning [start, end] as numbers (uint32 via >>> 0), `rangeToCidrs(start, end)` returning the minimal list of CIDR blocks covering the range exactly, and `coalesce(cidrs...
[ { "role": "user", "content": "Reservoir sampling with a statistical test, Python stdlib only. reservoir.py: `sample(iterable, k, rng)` implementing Algorithm R (single pass, O(k) memory — take an iterator, never call len or list on it), and `sample_weighted(iterable_of_item_weight_pairs, k, rng)` implementi...
[ { "role": "user", "content": "Count-min sketch in Python with an error-bound test. cms.py: class CountMinSketch(width, depth, seed) using pairwise-independent-ish hashing built from blake2b with per-row salts; add(item, count=1), estimate(item), merge(other) (same dims required — raise otherwise), plus clas...
[ { "role": "user", "content": "Implement HyperLogLog from the paper, Python stdlib only. hll.py: class HLL(p) with 2^p registers, add(item) hashing with blake2b (64-bit), estimate() including the standard bias correction for small ranges (linear counting when estimate <= 2.5*m and zero registers exist) and t...
[ { "role": "user", "content": "Sliding window maximum, quick but exact. Python window_max.py: `window_max(seq, k)` returning the max of each length-k window in O(n) total using a monotonic deque (collections.deque of indices). Pytest: fuzz vs the naive O(nk) slice-max oracle on 500 seeded random lists (lengt...
[ { "role": "user", "content": "Misra-Gries heavy hitters with its guarantee tested. Python misra_gries.py: `heavy_hitters(stream, k)` one-pass with at most k-1 counters, returning the surviving candidate dict; and `exact_check(stream, k)` a second-pass helper that filters candidates to those with true freque...
[ { "role": "user", "content": "Node.js streaming top-k word counter, tested end to end. topk.js: read stdin as a stream (readline interface), tokenize on non-letters, lowercase, count in a Map, and at end print the k most frequent words (k from argv, default 10) as \"count word\" lines, ties broken alphabeti...
[ { "role": "user", "content": "Implement the P-square (P2) streaming quantile estimator in Python — the classic five-marker algorithm from Jain & Chlamtac. p2.py: class P2Quantile(q) with add(x) and value(), maintaining 5 marker heights/positions with the parabolic adjustment formula and linear fallback; bef...
[ { "role": "user", "content": "Quickselect with median-of-three and a fallback guarantee, Python. quickselect.py: `select(a, k)` returning the k-th smallest (0-indexed) without fully sorting — in-place Hoare partition on a copied list, median-of-three pivoting, and an introselect-style depth cutoff that swit...
[ { "role": "user", "content": "Skip list ordered map in Python, seeded and benchmarked. skiplist.py: class SkipListMap with geometric level promotion (p=0.5, per-instance random.Random(seed)), set/get/delete, floor_key(k) and `range_items(lo, hi)` iterating in order. Correctness: fuzz 5000 seeded ops mirrore...
[ { "role": "user", "content": "Bloom filter with the math checked empirically, Python stdlib only. bloom.py: class BloomFilter.from_capacity(n, fp_rate) computing optimal bit count m = -n*ln(p)/(ln 2)^2 and k = (m/n)*ln 2 hash functions (double hashing from two blake2b-derived 64-bit values: h_i = h1 + i*h2 ...
[ { "role": "user", "content": "Deterministic Miller-Rabin for 64-bit integers, Python. miller_rabin.py: `is_prime(n)` using the known deterministic witness set [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] valid for n < 3.3 * 10^24, with proper handling of small n, even n, and witnesses >= n; then `next_prime...
[ { "role": "user", "content": "Karger's randomized min-cut with amplification, Python. karger.py: `min_cut_once(n, edges, rng)` contracting random edges (union-find based contraction is fine) down to 2 supernodes and returning the crossing-edge count, and `min_cut(n, edges, trials=None)` running the standard...
[ { "role": "user", "content": "A real bitset for Python, backed by ints. bitset.py: class BitSet(n) using a single Python int as backing store; set/clear/test(i), `count()` (popcount via int.bit_count), `next_set_bit(i)` (lowest set bit >= i, using (x >> i) and (v & -v) tricks — no bit-by-bit loops), iterate...
[ { "role": "user", "content": "Gray code, small and sharp. Python gray.py: `to_gray(n)`, `from_gray(g)` (the XOR-prefix inverse), and `gray_sequence(bits)` yielding the full 2^bits sequence. Pytest: round-trip for all n < 2^16; consecutive elements of gray_sequence(10) differ in exactly one bit (assert via (...
[ { "role": "user", "content": "Varint + ZigZag wire codec in Python with hypothesis. varint.py: `encode_uvarint(n) -> bytes` / `decode_uvarint(buf, offset) -> (value, new_offset)` (LEB128, 7 bits per byte, continuation high bit), `encode_zigzag(n)` / decode for signed ints, and `pack_ints(list) -> bytes` / u...
[ { "role": "user", "content": "Quick JavaScript bit-twiddling kit, node:test. bits.js: popcount32(x) via the parallel-bits masks (0x55555555 dance, no loops), clz32-free nlz(x) using math on your own (then cross-check against Math.clz32), isPow2, nextPow2 (the fill-right-then-increment trick, correct for 1 t...
[ { "role": "user", "content": "Meet-in-the-middle subset sum with bit tricks, Python. mitm.py: `subset_exists(nums, target)` for up to 40 ints (possibly negative): split, enumerate each half's sums by index-masking (iterate masks, reuse sums[mask without lowest bit] + value of lowest bit — no per-mask recomp...
[ { "role": "user", "content": "Expert build: an external merge sort that survives a crash, Python stdlib only. Package extsort/ with run_writer.py, merger.py, cli.py. Contract: sort a large text file of lines under a hard in-memory cap of MAX_LINES=10000 lines at once (enforce honestly: never hold more). Pha...
[ { "role": "user", "content": "Chunked dedup for files bigger than memory, Python. dedup.py CLI: `python dedup.py IN OUT --mem-lines 5000` removes duplicate lines while PRESERVING first-occurrence order, without ever holding more than mem-lines lines or an unbounded seen-set in memory. Approach: two passes —...
[ { "role": "user", "content": "Top-k from a file that must be streamed, Python. topk_file.py: `python topk_file.py FILE K` prints the K numerically largest values from a file of one integer per line using a size-K min-heap (heapq) in one pass — memory bounded by K, not file size. Also support `--bottom` for ...
[ { "role": "user", "content": "External group-by aggregation, Python. groupby_ext.py: input CSV with header \"user_id,amount\"; compute per-user count and sum WITHOUT loading all users into one dict — hash-partition rows into P=16 spill files by user_id, then aggregate each partition independently (assert pe...
[ { "role": "user", "content": "Grace hash join in Python, checked against SQLite. hashjoin.py: `python hashjoin.py LEFT.csv RIGHT.csv OUT.csv --key user_id --mem-rows 20000` performs an inner equi-join of two CSVs (arbitrary other columns preserved, left columns then right columns in output) with the grace s...
[ { "role": "user", "content": "Write a stable natural-merge sort and let hypothesis try to break it. Python project: sorting.py with `merge_sort(items, key=None)` — bottom-up merge sort that first detects existing ascending runs (natural merge), stable, returning a new list; then test_sorting.py using hypoth...
[ { "role": "user", "content": "Round-trip a binary serializer under hypothesis. Python binser.py: serialize(obj) -> bytes and deserialize(bytes) -> obj for the closed type family None, bool, int (arbitrary size, signed), str, bytes, list, dict-with-str-keys — nested arbitrarily. Format: 1 tag byte, then leng...
[ { "role": "user", "content": "Hypothesis stateful testing against a TTL-LRU cache, Python. Build lru_ttl.py: class TTLCache(capacity, ttl, clock=time.monotonic) with get/put; entries expire ttl seconds after their LAST write, capacity evicts least-recently-USED (get refreshes recency, not expiry); injectabl...
[ { "role": "user", "content": "A rope for big-string editing, driven by hypothesis stateful tests — this one is a proper project. Python rope/ package: balanced rope (concatenation tree with leaf strings capped at 64 chars, rebalance when depth exceeds a bound) supporting Rope.from_str, insert(i, s), delete(...
[ { "role": "user", "content": "Interval set with hypothesis as the referee. Python intervalset.py: class IntervalSet over integers with add(lo, hi), remove(lo, hi) (half-open), __contains__(x), total() (count of covered ints), and iter_ranges() yielding maximal disjoint sorted ranges — internal representatio...
[ { "role": "user", "content": "Benchmark question with a real answer: dict versus sorted-list-with-bisect for a membership-heavy workload. Python bench_membership.py: implement SortedListSet (bisect insort/index) and just use set/dict as the other side; workload generator (seeded) producing mixes of 90/10, 5...
[ { "role": "user", "content": "Substring search shoot-out with adversarial inputs, Python. bench_search.py: implement naive_find_all and kmp_find_all (both returning all overlapping match positions), plus a str.find-loop variant; correctness cross-check of all three on 500 seeded random cases first (pytest)....
[ { "role": "user", "content": "Top-k selection: heap vs sort vs partial sort, measured properly. Python bench_topk.py: three implementations of top-k largest from an unsorted list — full sorted()[-k:], heapq.nlargest, and a manual bounded min-heap loop; pytest correctness on seeded fuzz (ties included, k edg...
[ { "role": "user", "content": "Prefix-query benchmark: trie versus sorted list, Python. bench_prefix.py: implement a plain dict-node trie with `count_prefix(p)` and `list_prefix(p, limit)` (store subtree counts at nodes so count_prefix is O(len(p)), no subtree walk), and a bisect-based SortedWords with the s...
[ { "role": "user", "content": "Recursion vs table vs rolling arrays on one recurrence, Python. The recurrence: number of ways to tile a 4xN strip with dominoes and L-trominoes is annoying, so use the standard broken-profile DP; simpler statement to implement three ways: f(n) counts binary strings of length n...
[ { "role": "user", "content": "Fenwick vs segment tree vs naive list — one workload harness, three backends, Python. bench_rangesum.py: common interface (point_update(i, delta), range_sum(l, r)) implemented by NaiveList (O(1)/O(n)), Fenwick, and a non-lazy iterative segment tree; pytest fuzz proving all thre...
[ { "role": "user", "content": "A teammate swears this lower_bound is correct because \"the tests pass\" — their tests only used distinct elements. Drop this exact code into search.py:\n\ndef lower_bound(a, x):\n \"\"\"Return the first index i with a[i] >= x (len(a) if none).\"\"\"\n lo, hi = 0, len(a)\...
[ { "role": "user", "content": "This interval-merging function ships tomorrow and reviewers are suspicious of the sort key. Put it verbatim in merge_intervals.py:\n\ndef merge(intervals):\n \"\"\"Merge overlapping or touching closed intervals; return sorted disjoint list.\"\"\"\n out = []\n for s, e ...
[ { "role": "user", "content": "Inherited code, subtle off-by-one, wrong answers in production reports. Save exactly this as fenwick.py:\n\nclass Fenwick:\n \"\"\"1-indexed internally; public API is 0-indexed.\n prefix(i) returns the sum of a[0] through a[i] INCLUSIVE.\"\"\"\n def __init__(self, n):\...
[ { "role": "user", "content": "The on-call engineer says this heap \"mostly works\" — pops come out unsorted once in a while. Reproduce, then repair. minheap.py, exactly as written:\n\ndef sift_down(h, i):\n n = len(h)\n while True:\n l, r = 2 * i + 1, 2 * i + 2\n small = i\n if l ...
[ { "role": "user", "content": "Union-Find that silently splits components — a classic linking blunder. Put this in dsu.py as-is:\n\nclass DSU:\n def __init__(self, n):\n self.p = list(range(n))\n def find(self, x):\n while self.p[x] != x:\n self.p[x] = self.p[self.p[x]]\n ...
[ { "role": "user", "content": "Overlapping matches are being dropped by this string searcher and nobody noticed until the bioinformatics team complained. searcher.py, verbatim:\n\ndef prefix_function(p):\n f = [0] * len(p)\n k = 0\n for i in range(1, len(p)):\n while k > 0 and p[i] != p[k]:\n...
[ { "role": "user", "content": "This Dijkstra returns wrong distances on some graphs and the author cannot reproduce it — you will. dijkstra_buggy.py, exactly:\n\nimport heapq\n\ndef dijkstra(adj, src):\n \"\"\"adj: {node: [(neighbor, weight)]}; returns {node: dist} for reachable nodes.\"\"\"\n dist = {...
[ { "role": "user", "content": "JavaScript LRU cache with a recency bug that only shows under a specific access pattern. Save lru.js exactly as given, ES module:\n\nexport class LRU {\n constructor(cap) { this.cap = cap; this.m = new Map(); }\n get(k) {\n return this.m.has(k) ? this.m.get(k) : -1;\n }\n...
[ { "role": "user", "content": "Write wc.py, a Python 3 stdlib-only clone of wc supporting -l, -w, and -c flags plus multiple file arguments, reading stdin when no files are given. Counts are space-separated with the filename appended, and a total line appears when more than one file is given. Exit 0 on succe...