Bc-AI commited on
Commit
8b66dca
·
verified ·
1 Parent(s): 650704c

Upload 3 files

Browse files
orion-extreme-reasoning-0001.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {"messages": [{"role": "user", "content": "Design and implement an offline algorithm for dynamic connectivity in an undirected graph. The input is n and a sequence of operations add(u,v), remove(u,v), and connected(u,v); an edge may be added again after it has been removed, but duplicate active copies are forbidden, and every removal must refer to an active edge. Return one Boolean per connected query, in input order. Explain why a normal disjoint-set union structure is insufficient, give correctness and complexity arguments, and include executable tests for interval boundaries, repeated edge lifetimes, self-loops, and invalid operations."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: Connectivity is monotone only while edges are being added; a deletion can split a component, and ordinary DSU has no cheap inverse for a union. Since the complete operation sequence is known, convert each edge's active lifetime into a half-open interval [add_time, remove_time), or [add_time, Q) if it remains active. A segment tree over operation indices stores each edge in O(log Q) canonical nodes covering its lifetime. During a depth-first traversal, a rollback DSU contains exactly the edges stored at ancestors and the current node. At a query leaf, its connectivity answers therefore match the graph at that time. Use union by size but no path compression: every successful union records the changed child root and the previous parent size, so rollback is exact. Failed unions need no record because they change no state. Half-open intervals exclude the edge at its remove operation; leaves corresponding to add/remove operations are not queries, but this convention also makes the invariant unambiguous. Validate malformed operations and active-edge rules before traversal. Self-loops are valid and simply create no DSU change. With A edge lifetimes and Q operations, interval insertion creates O(A log Q) stored edges, each union/find costs O(log n) worst case, and traversal costs O(Q); total time is O((Q + A log Q) log n), with O(Q + A log Q + n) memory. The logarithmic DSU bound follows because union-by-size can increase a node's depth only when its component at least doubles; omitting path compression is essential to the simple rollback proof.<|end_reason|><|answer|>```python\nfrom typing import Iterable, List, Tuple\n\nOperation = Tuple[str, int, int]\n\n\ndef offline_connectivity(n: int, operations: Iterable[Operation]) -> List[bool]:\n \"\"\"Answer add/remove/connected operations on an undirected graph offline.\n\n Vertices are 0..n-1. Operations are 3-tuples such as\n (\"add\", u, v), (\"remove\", u, v), or (\"connected\", u, v).\n Parallel active copies of an undirected edge are rejected.\n \"\"\"\n if type(n) is not int or n <= 0:\n raise ValueError(\"n must be a positive integer\")\n ops = list(operations)\n q = len(ops)\n if q == 0:\n return []\n\n active = {} # normalized edge -> start time\n intervals = [] # (start, end, edge), with half-open time ranges\n for t, op in enumerate(ops):\n if not isinstance(op, (tuple, list)) or len(op) != 3:\n raise ValueError(f\"operation {t} must be a 3-item tuple/list\")\n kind, u, v = op\n if kind not in (\"add\", \"remove\", \"connected\"):\n raise ValueError(f\"unknown operation at index {t}: {kind!r}\")\n if type(u) is not int or type(v) is not int or not (0 <= u < n and 0 <= v < n):\n raise ValueError(f\"invalid vertex in operation {t}\")\n edge = (u, v) if u <= v else (v, u)\n if kind == \"add\":\n if edge in active:\n raise ValueError(f\"edge {edge} is already active\")\n active[edge] = t\n elif kind == \"remove\":\n if edge not in active:\n raise ValueError(f\"edge {edge} is not active\")\n intervals.append((active.pop(edge), t, edge))\n\n for edge, start in active.items():\n intervals.append((start, q, edge))\n\n tree = [[] for _ in range(4 * q)]\n\n def add_interval(node: int, left: int, right: int,\n ql: int, qr: int, edge: Tuple[int, int]) -> None:\n if ql >= right or qr <= left:\n return\n if ql <= left and right <= qr:\n tree[node].append(edge)\n return\n mid = (left + right) // 2\n add_interval(node * 2, left, mid, ql, qr, edge)\n add_interval(node * 2 + 1, mid, right, ql, qr, edge)\n\n for start, end, edge in intervals:\n if start < end:\n add_interval(1, 0, q, start, end, edge)\n\n parent = list(range(n))\n size = [1] * n\n history = [] # (child_root, parent_root, old_parent_size)\n\n def find(x: int) -> int:\n while parent[x] != x: # deliberately no path compression\n x = parent[x]\n return x\n\n def union(a: int, b: int) -> None:\n ra, rb = find(a), find(b)\n if ra == rb:\n return\n if size[ra] < size[rb]:\n ra, rb = rb, ra\n history.append((rb, ra, size[ra]))\n parent[rb] = ra\n size[ra] += size[rb]\n\n def rollback(snapshot: int) -> None:\n while len(history) > snapshot:\n child, root, old_size = history.pop()\n parent[child] = child\n size[root] = old_size\n\n answers = []\n\n def visit(node: int, left: int, right: int) -> None:\n snapshot = len(history)\n for u, v in tree[node]:\n union(u, v)\n if right - left == 1:\n kind, u, v = ops[left]\n if kind == \"connected\":\n answers.append(find(u) == find(v))\n else:\n mid = (left + right) // 2\n visit(node * 2, left, mid)\n visit(node * 2 + 1, mid, right)\n rollback(snapshot)\n\n visit(1, 0, q)\n return answers\n\n\nif __name__ == \"__main__\":\n # Boundary, repeated lifetime, connectivity split, and self-loop checks.\n ops = [\n (\"add\", 0, 1), (\"connected\", 0, 1),\n (\"add\", 1, 2), (\"connected\", 0, 2),\n (\"remove\", 1, 2), (\"connected\", 0, 2),\n (\"add\", 1, 2), (\"connected\", 0, 2),\n (\"add\", 3, 3), (\"connected\", 0, 3), (\"connected\", 3, 3),\n (\"remove\", 3, 3), (\"connected\", 0, 3), (\"connected\", 3, 3),\n ]\n assert offline_connectivity(4, ops) == [True, True, False, True, False, True, False, True]\n assert offline_connectivity(2, []) == []\n for bad in [\n [(\"remove\", 0, 1)],\n [(\"add\", 0, 1), (\"add\", 1, 0)],\n [(\"add\", 0, 2)],\n [(\"wat\", 0, 0)],\n [(\"add\", 0)],\n ]:\n try:\n offline_connectivity(2, bad)\n except ValueError:\n pass\n else:\n raise AssertionError(f\"invalid input was accepted: {bad!r}\")\n print(\"all offline-connectivity tests passed\")\n```\n\nThe API intentionally treats undirected edges as normalized endpoint pairs. A removed edge is absent beginning at its removal index; edge intervals are half-open. Queries at any later index observe the resulting graph. The validation pass ensures malformed histories fail before any answers are returned. This implementation is offline: it cannot emit answers before the operation sequence is complete.<|final|>"}]}
2
+ {"messages": [{"role": "user", "content": "We need a reliable event-driven service. An API request changes our database and must eventually publish an event to a broker; consumers update their own databases. Network failures can happen at any point. Explain a design that avoids lost events and duplicate business effects, and be precise about what ‘exactly once’ can and cannot mean."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: The unsafe design commits the business row and then publishes: a crash between those actions loses the event. Reversing the order can publish an event for a transaction that later rolls back. A database transaction cannot normally atomically commit with an independent broker, so the dependable boundary is the service database itself. Persist the business change and an outbox record in one local transaction, then relay the outbox at least once. A relay crash after broker acceptance but before recording success causes redelivery, so delivery is not exactly once. Make the effect idempotent instead: consumers insert a unique event ID into an inbox and apply their local business update in the same transaction. If either transaction rolls back, both inbox claim and effect roll back; if it commits, a duplicate cannot reapply the effect. This provides effectively-once state transition for a defined database scope, not magical exactly-once transport across arbitrary systems. External side effects require their own idempotency contract or a compensating workflow.<|end_reason|><|answer|>Use a **transactional outbox + idempotent consumer** pattern.\n\n1. **API transaction:** Validate the request and, in one database transaction, write the business state and an outbox row containing a stable event ID, event type, payload, creation time, and (if ordering matters) aggregate ID and sequence. A unique client idempotency key should also be stored with a request-payload hash and the eventual response. Repeating the same key and same payload returns the stored result; reusing it with a different payload is a conflict. This handles the case where the API committed but its response was lost.\n2. **Outbox relay:** A worker reads unpublished rows, publishes them, waits for broker acknowledgement, and only then marks them published. It must not mark first: a crash after marking but before sending would lose the event. A crash after sending but before marking may resend it; that is expected. Multiple workers can claim rows with database locking (for example, `FOR UPDATE SKIP LOCKED`), subject to the ordering policy described below.\n3. **Consumer transaction:** On receipt, begin a transaction in the consumer database. Insert `(consumer_name, event_id)` into an inbox table with a unique constraint, apply the local state change, and commit both together. If the insert conflicts, the event has already been applied and can be acknowledged without repeating the effect. If applying the effect fails, roll back the inbox insert too, allowing safe retry. Acknowledge the broker only after commit.\n\nThe guarantee is **at-least-once delivery plus deduplicated, atomic local effects**. It is often called effectively-once processing for a particular consumer database. It is not a guarantee that a network message is physically delivered once. If a consumer calls a payment gateway, sends email, or writes to another independent database, its local inbox transaction cannot atomically cover that external action. Use the external provider's idempotency key, a second outbox, or a saga with explicit compensation and reconciliation. Monitor the age/count of unpublished outbox rows, consumer lag, and repeated failures; define retention long enough that old broker redeliveries still encounter deduplication records.<|final|>"}, {"role": "user", "content": "Make this concrete for money transfers between two accounts. We require no overdrafts, idempotent API retries, and strict per-account event order. A consumer must update a balance projection. The relay can run on many workers, and a transfer emits a debit and a credit."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: The transfer's debit, credit, idempotency record, and two account-specific outbox rows must share one database commit; otherwise partial transfers or missing notifications are possible. Lock both account rows in deterministic account-ID order to avoid deadlocks, validate the source balance while locked, update balances, and increment each account's own monotonic version. Emit one event per account with that account's version and a common transfer ID. Partitioning by account preserves broker ordering only if the relay also prevents concurrent sends for the same account; a broker partition key alone cannot repair two workers publishing version 12 before version 11. Consumers should deduplicate by event ID and apply only the expected account version. A later version arriving early must be buffered/retried, not marked as fully applied. The two account events need not arrive atomically; if a downstream consumer requires an atomic cross-account view, it needs a transfer-level coordination rule, not merely per-account ordering.<|end_reason|><|answer|>A concrete relational design can use these logical tables:\n\n```sql\nCREATE TABLE api_requests (\n idempotency_key TEXT PRIMARY KEY,\n request_hash TEXT NOT NULL,\n transfer_id UUID NOT NULL UNIQUE,\n response_json JSONB NOT NULL\n);\n\nCREATE TABLE accounts (\n account_id BIGINT PRIMARY KEY,\n balance_minor BIGINT NOT NULL CHECK (balance_minor >= 0),\n version BIGINT NOT NULL DEFAULT 0\n);\n\nCREATE TABLE transfers (\n transfer_id UUID PRIMARY KEY,\n source_id BIGINT NOT NULL,\n destination_id BIGINT NOT NULL,\n amount_minor BIGINT NOT NULL CHECK (amount_minor > 0)\n);\n\nCREATE TABLE outbox (\n event_id UUID PRIMARY KEY,\n aggregate_id BIGINT NOT NULL, -- account ID\n aggregate_version BIGINT NOT NULL,\n transfer_id UUID NOT NULL,\n event_type TEXT NOT NULL,\n payload JSONB NOT NULL,\n published_at TIMESTAMPTZ,\n UNIQUE (aggregate_id, aggregate_version)\n);\n\nCREATE TABLE inbox (\n consumer_name TEXT NOT NULL,\n event_id UUID NOT NULL,\n aggregate_id BIGINT NOT NULL,\n aggregate_version BIGINT NOT NULL,\n PRIMARY KEY (consumer_name, event_id),\n UNIQUE (consumer_name, aggregate_id, aggregate_version)\n);\n```\n\nFor each API request, calculate a canonical request hash and enter a transaction. First claim the idempotency key. If it already exists with the same hash, return its recorded response; if the hash differs, reject the request rather than silently treating a different transfer as a retry. For a new request, lock both account rows in ascending `account_id` order, even though only the source is debited. Check account existence, amount bounds, and `source.balance >= amount`; then insert the transfer, debit/credit the two balances, increment each account version, and insert one outbox event for each account using the returned version. Persist the response and idempotency record in the same transaction. Any error, including insufficient funds, rolls everything back. Use integer minor units (cents), not binary floating point.\n\nThe common `transfer_id` ties the debit and credit events together; each event also carries its account ID, account version, signed delta, and resulting balance or enough data to compute it. Make transfer and ledger constraints unique by transfer/account/leg so accidental duplicate application is detectable. Ordered row locking prevents opposing transfers from deadlocking due to inconsistent lock order. The database transaction serializes concurrent debits against the same account, so two requests cannot both pass a stale balance check and overdraw it.\n\nFor strict per-account order, route each outbox event with `aggregate_id` as the broker partition key, and assign versions while holding the account lock. The relay must serialize publication per account: it may have many workers globally, but it must not allow two workers to publish versions `v` and `v+1` for the same account concurrently. One option is a leased per-account relay cursor/lock and selection of the lowest unpublished version; publish, wait for acknowledgement, then advance. Do not rely on `SKIP LOCKED` by itself to preserve order, because another worker could skip a locked version and publish a later one. If a publish outcome is uncertain, retry the same event ID and version before advancing. Broker partition ordering then preserves accepted order for that account. If the broker or relay can still expose gaps, the consumer version check detects them.\n\nThe balance-projection consumer keeps a per-account applied version. In one local transaction it checks the inbox uniqueness key and expected version. If `event.version == current_version + 1`, it applies the delta, records the inbox event, and advances the version atomically. If the version is at most current, it is a duplicate/stale delivery and can be acknowledged after confirming the dedupe record or projection state. If it is greater than `current_version + 1`, do not mark it applied: buffer it or retry until the gap is filled, and alert on a persistent gap. Commit before broker acknowledgement. The two account events may be observed at different times, so consumers requiring an atomic view of both sides must additionally wait for both legs of a transfer (or consume a transaction-level event into a suitably coordinated projection). Per-account ordering alone does not promise cross-account simultaneity.\n\nTest crash points explicitly: API response loss after commit must replay the same response; relay crash before send must leave a retryable row; crash after broker acknowledgement but before `published_at` must produce a harmless duplicate; consumer crash before commit must leave no inbox/effect; consumer crash after commit but before acknowledgement must be deduplicated. Also test simultaneous transfers from one source account, opposite-direction transfers, same idempotency key with changed payload, and out-of-order versions. This design prevents lost committed events and duplicate local balance effects, while honestly retaining at-least-once transport semantics.<|final|>"}]}
3
+ {"messages": [{"role": "user", "content": "There are n distinguishable balls independently assigned uniformly to m distinguishable boxes. Let K be the total number of colliding pairs, counting every pair of balls in the same box; thus a box with j balls contributes binomial(j,2), even when j is at least 3. Derive an exact computable distribution for K, give a dynamic program, prove it counts assignments correctly, and provide normalization and moment checks."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: Let X_i be the occupancy of labeled box i. The statistic is K = sum_i C(X_i,2), so triple occupancy contributes three pairs rather than one. A box receiving j of the still-unassigned labeled balls contributes C(j,2) to K. For a recurrence, dp[i,t,k] counts assignments of a fixed t-element labeled set to the first i labeled boxes with pair count k. If j of those t balls go into box i, there are C(t,j) choices; the remaining t-j balls form an assignment counted by dp[i-1,t-j,k-C(j,2)]. Summing over j gives a disjoint partition by the contents of the last box. The final count divided by m^n is the probability because all m^n functions from balls to boxes are equally likely. The equivalent exponential generating function encodes the same decomposition. Normalization follows because every assignment has one unique occupancy vector and one unique choice of last-box subset at each recurrence step. As an independent check, K is the sum of one indicator per unordered pair of balls; each indicator has probability 1/m, and distinct pair indicators are pairwise independent, including pairs sharing one ball. Thus E[K]=C(n,2)/m and Var(K)=C(n,2)(1/m)(1-1/m).<|end_reason|><|answer|>For each integer k, define `N(m,n,k)` as the number of assignments of the n labeled balls to the m labeled boxes for which K=k. Then\n\n\\[\n\\Pr(K=k)=\frac{N(m,n,k)}{m^n}.\n\\]\n\nA direct dynamic program is\n\n\\[\nD_{i,t,k}=\\sum_{j=0}^{t}\binom{t}{j}\\,D_{i-1,t-j,k-\binom{j}{2}},\n\\]\n\nwhere a term with a negative k-index is zero, and the base state is `D[0,0,0]=1` with all other `D[0,t,k]=0`. The answer is `N(m,n,k)=D[m,n,k]`. To see the recurrence, choose the subset of j labeled balls assigned to box i in `binom(t,j)` ways. The box contributes exactly `binom(j,2)` colliding pairs; the remaining labeled balls must be assigned to the first i−1 boxes. Different choices of the subset or of the earlier assignment are disjoint, and every assignment has exactly one such decomposition. This proves the recurrence by induction on i.\n\nOnly `0 <= t <= n` and `0 <= k <= binom(t,2)` need be retained. A sparse implementation stores maps from `(t,k)` to integer counts for each box layer; the recurrence uses exact integers, so probabilities are exact rationals `D[m,n,k]/m**n`. A dense implementation has a simple upper bound of O(m n^2 Kmax) arithmetic operations and O(n Kmax) rolling memory, where `Kmax=binom(n,2)`; sparse states are often much smaller. For a closed coefficient form, the exponential generating function is\n\n\\[\nN(m,n,k)=n!\\,[x^n z^k]\\left(\\sum_{j=0}^{n}\frac{x^j z^{\binom{j}{2}}}{j!}\right)^m.\n\\]\n\nEach box contributes `x^j/j!` for its j labeled occupants, and the factor z tracks its pair contribution. Raising to the mth power chooses the occupancy of every labeled box; multiplying the coefficient by n! assigns labels to the balls. This expression is also an independent derivation of the recurrence.\n\nUseful checks:\n\n* **Normalization:** `sum_k D[m,n,k] = m**n`. Summing over k removes the pair statistic; each of n balls independently chooses one of m boxes.\n* **Support:** `0 <= K <= binom(n,2)`. If n>0 and m>0, the minimum is at least `max(0,n-m)` because placing one ball in each box avoids collisions until boxes are exhausted; the DP automatically gives zero outside the feasible values.\n* **Mean:** Write `K=sum_{a<b} I_ab`, where I_ab is one if balls a and b share a box. Then `E[I_ab]=1/m`, so `E[K]=binom(n,2)/m`.\n* **Variance:** For distinct unordered pairs, the corresponding indicators are pairwise independent. If two pairs share a ball, the probability that all three balls choose the same box is `1/m^2`, equal to the product of the two pair-event probabilities; disjoint pairs are independent by independence of ball choices. Therefore `Var(K)=binom(n,2)(1/m)(1-1/m)`.\n\nFor a small explicit check, take n=3 and m=2. There are 8 assignments. Six have occupancy pattern (2,1), giving K=1; two have pattern (3,0), giving K=3. Hence `P(K=1)=6/8`, `P(K=3)=2/8`, and all other probabilities are zero. The probabilities sum to 1, the mean is `1.5 = binom(3,2)/2`, and the variance is `0.75 = 3(1/2)(1/2)`. This check also catches the common error of treating a triple occupancy as only one collision: its contribution is three unordered pairs.<|final|>"}]}
orion-extreme-reasoning-0002.jsonl ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"messages": [{"role": "user", "content": "Given a directed graph with nonnegative edge weights, return shortest distances from source s and one shortest path to every reachable vertex. Explain the heap invariant, stale entries, and the role of the weight restriction."}, {"role": "assistant", "content": "<|reason|>Dijkstra finalizes vertices in nondecreasing tentative-distance order. A lazy heap may contain obsolete keys; discarding a popped key that differs from the current distance preserves the invariant. Negative edges break the label-setting argument.<|end_reason|><|answer|>Initialize `dist[s]=0`, all other distances to infinity, and `parent[v]=None`. Repeatedly pop `(d,u)` from a min-heap; skip it unless `d == dist[u]`. For each edge `(u,v,w)`, if `d+w < dist[v]`, update the distance and parent and push the new pair. Reconstruct a path by following parents backward from v. With adjacency lists this takes O((V+E) log V) time and O(V+E) memory. Zero-weight edges are allowed. Negative weights are not: a vertex can be popped before a later negative edge improves it, so use Bellman–Ford or another algorithm appropriate to the graph. Unreachable vertices retain infinite distance and have no reconstructed path.<|final|>"}]}
2
+ {"messages": [{"role": "user", "content": "For a graph that may have negative edge weights, compute shortest distances from a source and identify which vertices are affected by reachable negative cycles. Give a proof-level description and complexity."}, {"role": "assistant", "content": "<|reason|>Any shortest simple path uses at most V−1 edges, so V−1 relaxation passes suffice absent a reachable negative cycle. An edge still relaxable afterward is reachable from such a cycle; reachability propagation marks all downstream affected vertices.<|end_reason|><|answer|>Set `d[s]=0` and other labels to infinity. Repeat V−1 times over every edge `(u,v,w)`, relaxing `d[v]` when `d[u]+w` is smaller; stop early if a pass changes nothing. On one additional scan, seed every v for which a reachable edge can still relax. Run graph traversal from these seeds: all reached vertices have distance `-infinity` in the sense that walks can make their cost arbitrarily small. Other finite labels are correct shortest distances, and remaining vertices are unreachable. The Bellman–Ford relaxation invariant proves all paths with at most k edges are represented after k passes. Runtime is O(VE), memory O(V+E).<|final|>"}]}
3
+ {"messages": [{"role": "user", "content": "Shortest paths are needed in a directed graph whose edge weights are only 0 or 1. Give an algorithm faster than a binary heap and explain why deque ordering is valid."}, {"role": "assistant", "content": "<|reason|>A relaxation adds either zero or one to the current distance. Thus newly discovered labels belong at the front or immediately after the current distance layer, which a deque represents without global heap ordering.<|end_reason|><|answer|>Use 0–1 BFS. Initialize `dist[s]=0` and a deque containing s. Pop from the front; for each outgoing edge `(u,v,w)`, if `dist[u]+w < dist[v]`, update it and push v to the front when w=0, otherwise to the back. As in lazy Dijkstra, skip stale queued entries if storing `(vertex,key)` pairs. Each successful relaxation is bounded by O(E) over the standard 0–1 BFS processing, giving O(V+E) time and O(V) auxiliary space. The method depends on weights being exactly 0 or 1; arbitrary nonnegative weights require a priority queue or another specialized structure.<|final|>"}]}
4
+ {"messages": [{"role": "user", "content": "Return a topological ordering of a directed graph, or report that it contains a cycle. Include isolated vertices and state why the algorithm detects every cycle."}, {"role": "assistant", "content": "<|reason|>Kahn's algorithm repeatedly removes zero-indegree vertices. If vertices remain but none has indegree zero, each remaining vertex has a predecessor in the remainder; following predecessors in a finite set eventually repeats a vertex and reveals a directed cycle.<|end_reason|><|answer|>Compute each indegree, enqueue every zero-indegree vertex, then repeatedly remove one, append it to the order, decrement the indegrees of its outgoing neighbors, and enqueue neighbors when their indegree reaches zero. If the output has V vertices, it is a topological order; otherwise report a cycle. Every edge is processed once, so time is O(V+E), with O(V+E) graph storage. Isolated vertices begin at indegree zero and are included. For an explicit cycle witness rather than a yes/no result, run a color-marked DFS on the unremoved subgraph and reconstruct a back edge through DFS parents.<|final|>"}]}
5
+ {"messages": [{"role": "user", "content": "Describe an O(V+E) method to find all strongly connected components (SCCs) and construct the condensation graph. Explain why the condensation is acyclic."}, {"role": "assistant", "content": "<|reason|>Tarjan's DFS maintains discovery indices, low-link values, and a stack of active vertices. A root with `low[v]=index[v]` closes one SCC. Contracting SCCs cannot leave a directed cycle, because that would make all components on it mutually reachable and therefore one SCC.<|end_reason|><|answer|>Run Tarjan's algorithm. On DFS entry assign `index[v]=low[v]`, push v, and mark it active. For a tree edge to w, recurse and lower `low[v]` with `low[w]`; for an edge to an active vertex, lower it with `index[w]`. When `low[v]==index[v]`, pop through v: those vertices form one SCC. Then map each original edge crossing component IDs to a condensation edge, optionally deduplicating pairs. Each vertex and edge is processed a constant number of times, so time is O(V+E) and auxiliary space is O(V). A common bug is using `low[w]` for a back edge to an already discovered active vertex; that case uses `index[w]`.<|final|>"}]}
6
+ {"messages": [{"role": "user", "content": "Find every bridge in an undirected multigraph. Explain how to avoid falsely treating a parallel edge as a bridge and give the low-link condition."}, {"role": "assistant", "content": "<|reason|>A DFS tree edge (v,w) is a bridge exactly when the subtree at w has no back edge to v or any ancestor, expressed as `low[w] > tin[v]`. Parent vertices alone are insufficient in a multigraph; the DFS must skip only the exact parent edge ID.<|end_reason|><|answer|>Give each undirected edge a unique ID and store `(neighbor, edge_id)` at both endpoints. DFS from every unvisited vertex, recording entry time `tin` and `low`. Skip the incoming edge ID, recurse on tree edges, then set `low[v]=min(low[v],low[w])`; for an already visited endpoint reached by a non-parent edge, set `low[v]=min(low[v],tin[w])`. Report tree edge `(v,w)` as a bridge iff `low[w] > tin[v]`. This runs in O(V+E). Parallel edges correctly provide a back edge: only one copy is skipped as the parent edge, while the other lowers the child’s low-link value. Self-loops never become bridges.<|final|>"}]}
7
+ {"messages": [{"role": "user", "content": "Give a criterion for whether a connected undirected weighted graph has a unique minimum spanning tree (MST), including tied edge weights. A simple ‘all weights distinct’ condition is too strong."}, {"role": "assistant", "content": "<|reason|>Process equal-weight edges as a group after contracting components formed by strictly lighter edges. A cycle in the resulting multigraph permits alternative choices at that weight; if every group is acyclic after contraction, each Kruskal decision is forced.<|end_reason|><|answer|>Sort edges by weight and maintain a DSU containing only unions from strictly smaller weights. For one equal-weight group, map endpoints to current DSU roots and discard edges whose endpoints already coincide. The remaining temporary multigraph must be a forest for uniqueness. If it has a cycle (parallel edges count as a cycle of length two), at least two ways to connect those contracted components have the same cost, so the MST is not unique. After checking the whole group, union its original edges in the DSU and continue. The graph must be connected for an MST to exist. This criterion follows from the exchange property of spanning trees: any cycle in a tied contracted group gives an equal-cost exchange; absent such cycles, every accepted connection is forced. Complexity is O(E log E) for sorting plus near-linear DSU work.<|final|>"}]}
8
+ {"messages": [{"role": "user", "content": "Explain Dinic's maximum-flow algorithm, including residual reverse edges, level graphs, and when flow can be augmented. State a safe complexity bound for general capacities."}, {"role": "assistant", "content": "<|reason|>Residual reverse edges let later augmentations cancel earlier choices. BFS levels restrict blocking-flow search to shortest residual paths; once no source-to-sink path exists in the residual graph, the max-flow/min-cut theorem certifies optimality.<|end_reason|><|answer|>For each directed capacity edge, store a residual reverse edge initially of capacity zero. Repeatedly BFS from source to assign residual levels. If the sink is unreachable, stop. Otherwise use DFS with current-edge pointers to send flow only along residual edges from level i to i+1 until no more source-to-sink flow exists in that level graph. Update forward and reverse residual capacities for every augmentation. The result is a blocking flow; repeat BFS. Dinic is O(V^2 E) in general directed graphs with integral capacities; special graph classes admit stronger bounds. Capacities need not be unit, but the implementation should use a numeric type large enough for the total flow. A frequent bug is failing to pair reverse edges by stable indices, which breaks parallel-edge handling.<|final|>"}]}
9
+ {"messages": [{"role": "user", "content": "For a flow network with integer costs that may be negative but has no negative-cost cycle reachable in the usable residual network, describe successive shortest augmenting path with potentials. Explain why raw Dijkstra is not initially valid."}, {"role": "assistant", "content": "<|reason|>Reduced costs `c(u,v)+p[u]-p[v]` become nonnegative when potentials are feasible. Dijkstra can then find a shortest residual augmenting path; updating potentials by the reduced distances preserves feasibility for future iterations.<|end_reason|><|answer|>Initialize feasible vertex potentials using Bellman–Ford when negative residual costs are present, or use zero potentials if all usable costs are nonnegative. On each iteration run Dijkstra on positive-capacity residual edges with reduced cost `c+p[u]-p[v]`; update potentials for reached vertices by their reduced distances. Trace the predecessor path, augment by the minimum residual capacity on it, and add `flow * original_path_cost` to total cost. Stop when the sink is unreachable or required flow is sent. This algorithm needs no reachable negative-cost residual cycle for the chosen optimization model; if such a cycle exists, first define whether circulation improvements are allowed and handle cycle cancellation/min-cost circulation appropriately. Complexity is O(F E log V) for unit augmentations and can depend on the number of augmentations; capacity scaling or cost-scaling methods may be preferable for large capacities.<|final|>"}]}
10
+ {"messages": [{"role": "user", "content": "Find a maximum matching in a bipartite graph efficiently. Explain the layered augmenting-path idea and why searching every augmenting path one at a time is slower."}, {"role": "assistant", "content": "<|reason|>Hopcroft–Karp finds a maximal set of shortest augmenting paths per phase. The layered graph prevents paths from being arbitrarily long within a phase, yielding O(E sqrt(V)) rather than the O(VE) bound of basic augment-one-path algorithms.<|end_reason|><|answer|>Maintain `mateL` and `mateR`. In each phase, BFS from all unmatched left vertices to build distances through unmatched and matched edges, stopping at the shortest layer that reaches an unmatched right vertex. DFS follows only edges respecting these layers to find a maximal collection of vertex-disjoint shortest augmenting paths; flip matched status along each path. Repeat until no augmenting path exists. By Berge’s lemma, a matching is maximum exactly when no augmenting path exists. Hopcroft–Karp runs in O(E sqrt(V)) time and O(V+E) memory. Handle unmatched right vertices as terminal states in BFS/DFS rather than assigning them ordinary left-layer distances.<|final|>"}]}
11
+ {"messages": [{"role": "user", "content": "Reduce a 2-SAT formula to graph reachability, test satisfiability, and explain what information SCCs provide. A clause has at most two literals."}, {"role": "assistant", "content": "<|reason|>Each clause `(a OR b)` is equivalent to implications `not a -> b` and `not b -> a`. If a literal and its negation share an SCC, each implies the other and neither truth assignment is possible. Otherwise the condensation ordering yields a satisfying assignment.<|end_reason|><|answer|>Create two vertices per variable, one for each literal. For `(a OR b)`, add edges `¬a -> b` and `¬b -> a`. Compute SCCs. The formula is unsatisfiable iff some variable’s two literal vertices lie in the same SCC. Otherwise topologically order the SCC condensation and set each variable true exactly when its positive-literal SCC occurs later than its negative-literal SCC in that order. Complementary implication edges guarantee this assignment respects every implication; verify all clauses as a defensive check. Tarjan or Kosaraju gives O(V+E) time and space, linear in formula size. For unit clause `(a)`, add `¬a -> a`. Preserve a clear literal-indexing convention; swapped positive/negative indices are a common source of incorrect assignments.<|final|>"}]}
12
+ {"messages": [{"role": "user", "content": "A Fenwick tree stores nonnegative integer frequencies. Design a method to find the smallest index whose prefix sum is at least k, in O(log n), and state its preconditions."}, {"role": "assistant", "content": "<|reason|>Fenwick binary lifting constructs the answer bit by bit using the largest power-of-two step. Nonnegative frequencies make prefix sums monotone, so skipping a Fenwick block is valid exactly when its sum remains below k.<|end_reason|><|answer|>Require `1 <= k <= total_frequency` and all point frequencies nonnegative. Starting with index 0 and the largest power of two no greater than n, test candidate `index+step`; if it is within n and its accumulated Fenwick block sum is less than k, advance the index and subtract that block sum from k. Halve step until zero; the answer is `index+1`. The standard Fenwick internal representation supports this through binary lifting without a separate binary search, so time is O(log n). Negative updates would destroy monotonic prefix sums and invalidate the selection operation, even though ordinary prefix-sum queries would still work.<|final|>"}]}
13
+ {"messages": [{"role": "user", "content": "Implement range-add and range-minimum queries on an array in O(log n) per operation. Explain the lazy propagation invariant and what must happen before descending."}, {"role": "assistant", "content": "<|reason|>A node stores the minimum of its segment including all updates applied to that whole segment. Its lazy value records an addition owed uniformly to descendants; pushing it before a partial descent preserves child values and the parent minimum.<|end_reason|><|answer|>Build a segment tree whose node stores `minimum` and `lazy_add`. For a full-cover update by x, add x to both fields. For a partial update, push the node’s lazy value to both children, clear it, recurse, then recompute the parent minimum as the smaller child minimum. For a query, return the node minimum on full cover; otherwise push before recursing and take the minimum of relevant children. Time per update/query is O(log n) for a standard interval decomposition, and storage is O(n). Use a consistent half-open or closed interval convention throughout. Forgetting the push before partial queries is a classic bug: the parent can be correct while child summaries are stale.<|final|>"}]}
14
+ {"messages": [{"role": "user", "content": "For a static array, answer range-minimum queries in O(1) after preprocessing. Explain why overlapping sparse-table blocks are safe for minimum but not for every operation."}, {"role": "assistant", "content": "<|reason|>A query interval can be covered by two power-of-two blocks of length `2^k` that overlap. Minimum is idempotent (`min(x,x)=x`), so duplicated elements do not change the result; sum is not idempotent.<|end_reason|><|answer|>Build `st[k][i]`, the minimum over the length-`2^k` block starting at i. Level k is the min of two adjacent level-(k−1) blocks. For inclusive query [L,R], let `k=floor(log2(R-L+1))`; return `min(st[k][L], st[k][R-2^k+1])`. Preprocessing and memory are O(n log n); each query is O(1). This two-block trick also works for other associative idempotent operations such as gcd, but not sum or xor in general. For a static sum array use prefix sums; for updates use a Fenwick or segment tree.<|final|>"}]}
15
+ {"messages": [{"role": "user", "content": "Preprocess a rooted tree for lowest common ancestor queries. Give the binary-lifting recurrence, query method, and complexity."}, {"role": "assistant", "content": "<|reason|>Store `up[j][v]`, the ancestor 2^j edges above v. Every jump decomposes into powers of two; after equalizing depths, lift both vertices from the largest jump downward whenever their ancestors differ.<|end_reason|><|answer|>Root the tree and compute depth and `up[0][v]` by DFS/BFS. Build `up[j][v]=up[j-1][up[j-1][v]]` through `ceil(log2 n)` levels. To query u,v, lift the deeper vertex to equal depth. If they coincide, return it. Otherwise descend j from largest to zero, lifting both whenever their 2^j ancestors differ; their parent is the LCA. Preprocessing and storage are O(n log n); each query is O(log n). For a forest, add a component ID and reject or separately handle pairs from different components.<|final|>"}]}
16
+ {"messages": [{"role": "user", "content": "For each vertex v in a tree, compute the sum of distances from v to all vertices in O(n). Derive a rerooting formula from one DFS result."}, {"role": "assistant", "content": "<|reason|>Choose a root r. A postorder computes subtree sizes and the distance sum at r. Moving the root across edge parent->child decreases distances to the child’s subtree by one and increases distances to all other vertices by one.<|end_reason|><|answer|>Let `size[v]` be the number of vertices in v’s rooted subtree. Compute `ans[root]=sum_v depth[v]`. For a child c of v, use `ans[c]=ans[v] + n - 2*size[c]`: the `size[c]` vertices become one closer, while the other `n-size[c]` become one farther. A postorder for sizes and a preorder for answers each take O(n); total time is O(n), memory O(n). This argument assumes an unweighted tree, so each edge has length one. For weighted edges, replace the change by `weight*(n-2*size[c])`.<|final|>"}]}
17
+ {"messages": [{"role": "user", "content": "State and use the degree conditions for a directed Euler trail, and describe how to construct the trail. Include the connectivity condition often omitted from degree-only tests."}, {"role": "assistant", "content": "<|reason|>Degree balance is necessary but does not prevent disconnected edge-bearing components. Weak connectivity of the nonzero-degree support plus the correct imbalance pattern is sufficient for a directed Euler trail; Hierholzer then consumes each edge once.<|end_reason|><|answer|>For a circuit, every non-isolated vertex must have equal indegree and outdegree, and all non-isolated vertices must be connected in the underlying undirected graph. For an open trail, exactly one vertex has out−in=1 (start), exactly one has in−out=1 (end), all others balance, and the same support-connectivity condition holds. Run iterative Hierholzer from the start (or any non-isolated vertex for a circuit), advancing a per-vertex adjacency cursor and appending a vertex only after all outgoing edges are consumed; reverse the resulting sequence. Verify that the output uses exactly E edges. Complexity is O(V+E). Preserve edge IDs if parallel edges are allowed.<|final|>"}]}
18
+ {"messages": [{"role": "user", "content": "Given many patterns and a long text, report all pattern occurrences in O(text length + total pattern length + matches). Describe Aho–Corasick failure links and output handling."}, {"role": "assistant", "content": "<|reason|>The trie shares pattern prefixes; failure links recover the longest suffix that is also a trie prefix after a mismatch. Each text character advances through amortized failure transitions, while terminal outputs identify patterns ending at the current position.<|end_reason|><|answer|>Insert all patterns into a trie, storing pattern IDs at terminal nodes. BFS computes each node’s failure link and propagates terminal outputs from its failure state (or stores output links to avoid copying large lists). Scan the text: while the current transition is absent and the state is non-root, follow failure links; then take the transition if present, otherwise remain at root. Emit every pattern ID terminating at the state/output chain. Construction is O(total pattern length times alphabet-transition lookup cost); scanning is O(text length + matches) with suitable transitions. For a large alphabet, use maps or compressed edges rather than a dense alphabet-sized table.<|final|>"}]}
19
+ {"messages": [{"role": "user", "content": "Explain KMP for finding every occurrence of a pattern in a streaming text without backing up the text cursor. Define the prefix function and the mismatch transition."}, {"role": "assistant", "content": "<|reason|>The prefix function records the longest proper border of each pattern prefix. After a mismatch, that border is the largest suffix that can still match, so already-consumed text characters need not be revisited.<|end_reason|><|answer|>Compute `pi[i]`, the length of the longest proper prefix of `P[0..i]` that is also its suffix. While scanning text character c with matched length q, repeatedly set `q=pi[q-1]` while q>0 and `P[q]!=c`; then increment q on a match. When q reaches pattern length m, report the start index and reset q to `pi[m-1]` to permit overlaps. Preprocessing is O(m), scanning O(n), and memory O(m). For an empty pattern, define behavior explicitly (commonly matches at all n+1 boundaries) rather than running this loop unchanged.<|final|>"}]}
20
+ {"messages": [{"role": "user", "content": "Return a longest increasing subsequence (strictly increasing) in O(n log n), not just its length. Explain how parent pointers reconstruct one answer and how to handle duplicates."}, {"role": "assistant", "content": "<|reason|>Maintain the smallest ending value for each subsequence length. Binary search the first tail greater than or equal to x for strict LIS; replacing that tail preserves the best extension potential. Record the index that supplied the previous length at insertion time.<|end_reason|><|answer|>For each input value x, find `p=lower_bound(tails,x)`. Set its predecessor to the index currently stored for length p (if p>0), then replace the tail and its representative index at p; if p equals the tail-array length, append. The final representative at the last length traces parents backward to produce an LIS. The length is O(n log n), reconstruction costs O(n) including the trace, and storage is O(n). Using `upper_bound` instead would compute a nondecreasing subsequence, not a strictly increasing one. Equal values replace a tail but do not extend its length.<|final|>"}]}
21
+ {"messages": [{"role": "user", "content": "Find the maximum-sum subarray whose length is between L and R inclusive. Give an O(n) algorithm and explain the index window."}, {"role": "assistant", "content": "<|reason|>With prefix sums P, a subarray ending at i and valid length has sum `P[i]-P[j]` for `j in [i-R,i-L]`. Thus each endpoint needs the minimum prefix value in a sliding index window, maintained by a monotone deque.<|end_reason|><|answer|>Set `P[0]=0`. For each end index i from L through n, insert start index `j=i-L` into a deque ordered by increasing `P[j]`, removing dominated larger/equal values from the back. Remove indices smaller than `i-R` from the front. The best valid sum ending at i is `P[i]-P[deque.front]`; record indices if required. Each index enters and leaves once, so time O(n), memory O(n) for prefix sums or O(R) with streaming storage. This formulation handles negative values correctly; initializing the answer to zero would be wrong if every allowed segment has negative sum.<|final|>"}]}
22
+ {"messages": [{"role": "user", "content": "Maintain the median of a sliding window of integers under insertion and expiration in O(log w) amortized time. Explain why two ordinary heaps need extra bookkeeping."}, {"role": "assistant", "content": "<|reason|>A max-heap for the lower half and min-heap for the upper half give the median at their roots, but heaps cannot efficiently delete arbitrary expired values. Delayed deletion counts plus logical heap sizes make expiration lazy while preserving balance.<|end_reason|><|answer|>Keep the lower heap’s size equal to the upper size or one larger. Insert into the appropriate heap, mark expired values in a delayed-deletion counter, prune marked roots before reading or rebalancing, and move roots if the size invariant is violated. Use logical sizes that exclude delayed items. A multiset or balanced tree is often simpler; with two heaps and delayed deletion, each insertion/expiration is O(log w) amortized, though stale buried entries may require periodic heap rebuilding to bound memory under long streams. For even w, specify whether the median is the lower middle, upper middle, or arithmetic mean. Duplicate values require counts, not a single Boolean deleted flag.<|final|>"}]}
23
+ {"messages": [{"role": "user", "content": "Support range addition and range-sum queries on a one-indexed array with two Fenwick trees. Derive the prefix-sum formula and update signs."}, {"role": "assistant", "content": "<|reason|>A difference array turns range addition into two point changes. The prefix sum of the original array is a weighted prefix of differences; maintaining sums of d[i] and (i−1)d[i] yields `prefix(x)=x*sumD−sumWeighted`.<|end_reason|><|answer|>For adding delta on [l,r], update difference d at l by +delta and at r+1 by −delta. Maintain Fenwick B1 over d and B2 over `(i−1)d`. Therefore update B1 at l/r+1 by ±delta, and B2 at those indices by `±delta*(index−1)`. Then `prefix(x)=x*query(B1,x)-query(B2,x)`, and `sum(l,r)=prefix(r)-prefix(l-1)`. Each update/query is O(log n), storage O(n). Ensure the Fenwick trees have room for r+1 or guard the n+1 update; the latter is irrelevant to queries up to n but should be handled safely.<|final|>"}]}
24
+ {"messages": [{"role": "user", "content": "Compute the convex hull of planar points in O(n log n), returning only extreme vertices and excluding collinear points along hull edges. State orientation and duplicate handling."}, {"role": "assistant", "content": "<|reason|>Sort and deduplicate points, then build lower and upper chains. A non-left turn indicates the latest point cannot be an extreme vertex under the requested policy, so pop it; using a non-strict turn test removes boundary-collinear interior points.<|end_reason|><|answer|>Sort points lexicographically and deduplicate. For each chain, append points in sorted order and while the last three have cross product `<= 0`, remove the middle point. Build the upper chain in reverse order and concatenate after dropping duplicated endpoints. The result is counterclockwise for a nondegenerate set. Sorting costs O(n log n); the chain construction is O(n) because each point is pushed and popped at most once. If all points are collinear, this convention returns the two endpoints (one point for a singleton). Change `<=` to `<` if boundary-collinear points should be retained.<|final|>"}]}
25
+ {"messages": [{"role": "user", "content": "Design an O(n log n) closest-pair algorithm for planar points. Explain how to retain the complexity when examining the vertical strip."}, {"role": "assistant", "content": "<|reason|>Divide by x-coordinate and recursively compute each half’s minimum distance. Merge points by y-coordinate; in the strip, geometric packing bounds the number of later neighbors that need checking to a constant (seven under the standard Euclidean argument). Sorting each strip from scratch would add a log factor.<|end_reason|><|answer|>Sort points by x once and handle duplicate coordinates immediately (distance zero). Recursively split by x index, returning the minimum distance and the subproblem’s points ordered by y; merge the y-lists in linear time. Form a strip of points whose horizontal distance from the split is less than the current best, already ordered by y, and compare each point with at most the next seven candidates. Packing disjoint disks of radius half the current best gives this constant bound. The recurrence is O(n log n), with O(n) auxiliary storage. Use squared distances in comparisons to avoid unnecessary square roots; take one square root for the final answer.<|final|>"}]}
26
+ {"messages": [{"role": "user", "content": "Given intervals with start, finish, and value, choose a maximum-value non-overlapping subset in O(n log n). Define how touching endpoints are treated."}, {"role": "assistant", "content": "<|reason|>Sort intervals by finish time. For interval i, the optimal solution either excludes it or includes it plus the optimum among intervals finishing no later than its start; binary search finds that compatible prefix.<|end_reason|><|answer|>Sort by nondecreasing finish time and let `p(i)` be the last earlier interval with `finish <= start_i` for half-open intervals. Compute `dp[i]=max(dp[i-1], value_i+dp[p(i)])`, with `dp[0]=0`; store the chosen branch to reconstruct the subset. Binary-searching p for every interval and sorting costs O(n log n), and DP is O(n). This permits negative-value intervals to be skipped. For closed intervals where touching counts as overlap, compatibility must instead use `finish < start`. Clarify whether zero-length intervals are allowed, since endpoint conventions affect their compatibility.<|final|>"}]}
27
+ {"messages": [{"role": "user", "content": "Solve 0/1 knapsack and reconstruct a chosen item set. Explain how a one-dimensional value DP differs from reconstruction storage."}, {"role": "assistant", "content": "<|reason|>Each item must be used at most once, so capacities must be processed downward in the one-dimensional recurrence. Reconstructing choices from a compressed array is not generally possible after later overwrites unless extra decisions or divide-and-conquer reconstruction are stored.<|end_reason|><|answer|>For item i with weight w and value v, update `dp[c]=max(dp[c], dp[c-w]+v)` for c from W down to w. This computes the optimum value in O(nW) time and O(W) memory. To reconstruct simply, use a two-dimensional table `dp[i][c]` and backtrack from `(n,W)`, choosing item i when its inclusion gives the stored optimum and the previous-row value is lower; memory becomes O(nW). Alternatively use divide-and-conquer reconstruction to reduce memory. Downward capacity iteration is essential: upward iteration solves the unbounded variant. State whether zero-weight items are allowed and ensure each is considered only once.<|final|>"}]}
28
+ {"messages": [{"role": "user", "content": "Compute the longest common subsequence (LCS) of two strings in O(mn) time but O(min(m,n)) working memory, and reconstruct an actual subsequence."}, {"role": "assistant", "content": "<|reason|>Hirschberg splits one string in half. Forward and reverse linear-space DP rows measure every possible join point in the other string; a maximizing split preserves an optimal LCS, so recurse on two smaller subproblems.<|end_reason|><|answer|>Use the standard LCS row DP to compute lengths for A’s left half against every prefix of B, and for the reversed right half against every suffix. Choose split j maximizing `forward[j]+backward[|B|-j]`, then recurse on `(A_left,B_prefix)` and `(A_right,B_suffix)`. Empty inputs return empty; a one-character A returns it iff it occurs in B. Concatenate the recursive results. The recurrence keeps O(mn) total time while rows use O(min(m,n)) space when the shorter dimension is chosen for the row; recursion and output add O(m+n) stack/output space. Validate by checking the returned sequence is a subsequence of both inputs and matches the DP optimum.<|final|>"}]}
29
+ {"messages": [{"role": "user", "content": "Give a weighted edit-distance recurrence with insertion, deletion, and substitution costs. Explain when the usual recurrence does not model transposition."}, {"role": "assistant", "content": "<|reason|>An optimal edit script’s last operation is insertion, deletion, or substitution/match, giving three predecessor states. Adjacent transposition is a different operation and requires a distinct recurrence and careful definition of whether transpositions overlap.<|end_reason|><|answer|>Let `D[i][j]` be the minimum cost to convert the first i source characters to the first j target characters. Set `D[0][j]=j*insert_cost` and `D[i][0]=i*delete_cost`. Then `D[i][j]=min(D[i-1][j]+delete_cost, D[i][j-1]+insert_cost, D[i-1][j-1]+(0 if characters match else substitute_cost))`. Compute row by row in O(mn) time and O(min(m,n)) value-only memory, swapping insertion/deletion roles if dimensions are swapped. This is Levenshtein-style distance; it does not allow transposition. Damerau–Levenshtein variants need extra state and must specify the transposition model.<|final|>"}]}
30
+ {"messages": [{"role": "user", "content": "Explain A* search for a shortest path and distinguish admissibility from consistency. What can an implementation safely do when a heuristic is admissible but inconsistent?"}, {"role": "assistant", "content": "<|reason|>Admissibility ensures the heuristic never overestimates remaining optimal cost, supporting optimal goal termination when the frontier is handled correctly. Consistency is a triangle inequality that makes f-scores nondecreasing along paths and prevents a settled node from needing reopening.<|end_reason|><|answer|>Prioritize nodes by `f=g+h`, where g is the best known path cost and h estimates remaining cost. An admissible heuristic (`h(v) <= true_cost_to_goal`) supports optimal A*; with a consistent heuristic, closed nodes need not be reopened. With an admissible but inconsistent heuristic, a node’s g-value can improve after it was expanded, so permit reopening and discard stale heap entries. Require nonnegative edge costs and `h(goal)=0` for the standard guarantee. h=0 reduces A* to Dijkstra. A heuristic that overestimates may return a suboptimal route, even if it is otherwise informative.<|final|>"}]}
31
+ {"messages": [{"role": "user", "content": "Design a cache-aside service for expensive database reads. It has multiple application replicas, bursts of identical requests, and occasionally stale data. Describe stampede prevention and invalidation tradeoffs."}, {"role": "assistant", "content": "<|reason|>Cache-aside alone permits many replicas to miss simultaneously and stampede the origin. Per-key request coalescing, bounded stale serving, and TTL jitter reduce load, but invalidation races can still write an old value after a newer update.<|end_reason|><|answer|>On a miss, coalesce requests for the same key within each process and use a distributed lease only if cross-replica coalescing is worth its coordination cost. Recheck the cache after acquiring the lease; set a lease expiry so crashed owners do not block refresh forever. Use TTL jitter to avoid synchronized expirations and serve stale data only where the product’s freshness contract allows it. Invalidate or update cache entries through an outbox-driven change stream, and monitor origin load, stale age, and lease contention. Cache failures should degrade to the origin with concurrency limits rather than fail the whole service.<|final|>"}, {"role": "user", "content": "A delayed invalidation from an older database write can arrive after a newer value was cached. How do I prevent that stale event from overwriting fresh data?"}, {"role": "assistant", "content": "<|reason|>Ordering by event arrival is insufficient: a late old event can win. Add a monotonic source version and make cache writes conditional on version, so only newer state can replace older state; deletion also needs a versioned tombstone.<|end_reason|><|answer|>Attach a per-key monotonic version to database changes, ideally incremented in the same transaction as the row update. Store `(version,value)` in cache and apply an update only if its version is greater than the cached version using an atomic compare-and-set or script. Represent deletion as a versioned tombstone retained long enough to reject delayed old updates. If per-key versions are unavailable, use a generation token/fencing token from a reliable sequencer; wall-clock timestamps are vulnerable to clock skew. Pub/sub invalidation improves freshness but should not be the sole correctness mechanism if messages can be lost.<|final|>"}]}
32
+ {"messages": [{"role": "user", "content": "Implement a token bucket rate limiter for a single API process and then explain how to make its state safe across many replicas."}, {"role": "assistant", "content": "<|reason|>A bucket stores available tokens and the last refill time. On each request, refill by elapsed time times rate, cap at capacity, then atomically consume cost if enough tokens remain. Distributed correctness requires the read-modify-write to be atomic.<|end_reason|><|answer|>For capacity B and refill rate r tokens/second, keep `(tokens,last_time)`. At time now, set `tokens=min(B,tokens+r*(now-last_time))`; allow a request of cost c iff tokens≥c, then subtract c and persist the new state. Reject or delay otherwise. For one process, a lock protects each bucket. Across replicas, execute the calculation atomically in a shared store, such as a Redis script using server time. Expire idle state after a suitable horizon and define behavior during store outages—fail open protects availability but weakens the limit; fail closed protects quotas but rejects legitimate traffic.<|final|>"}, {"role": "user", "content": "The quota is global across regions and must never exceed 1,000 requests per minute, even during a network partition. Is a local Redis bucket in each region enough?"}, {"role": "assistant", "content": "<|reason|>Independent regional buckets multiply the allowance, and a partition prevents exact coordination without sacrificing availability. Strict global enforcement requires a centralized/consensus-backed counter or preallocated regional quotas whose sum is bounded by the global limit.<|end_reason|><|answer|>A local bucket per region is not enough: if each gets capacity 1,000, N regions can admit roughly N,000 requests. For a strict hard cap, serialize admissions through a strongly consistent shared limiter, accepting its latency and partition-availability tradeoffs. A scalable alternative allocates leases/credits to regions with quotas summing to at most 1,000 per minute; regions may underuse capacity but cannot exceed the global cap while disconnected. Define window/refill semantics and clock source precisely. If the requirement is approximate rather than hard, independent buckets with conservative quotas and reconciliation may be acceptable, but label the overshoot bound.<|final|>"}]}
33
+ {"messages": [{"role": "user", "content": "Two doctors are on call; each transaction reads that at least one is on call and then may turn itself off. Under snapshot isolation, explain the anomaly and give two sound fixes."}, {"role": "assistant", "content": "<|reason|>Both transactions can read the same valid snapshot, update different rows, and commit; neither writes the row changed by the other, so snapshot isolation’s write-write conflict check does not detect the invariant violation. This is write skew.<|end_reason|><|answer|>If both doctors are initially on call, concurrent transactions can each observe the other on call and turn off their own row. The final state violates the invariant although both snapshots were locally valid. One fix is serializable isolation with serialization-failure retries. Another is to lock a shared guard row or perform an atomic conditional update that makes the invariant a single write conflict. Merely adding a check constraint on each individual row cannot enforce a cross-row invariant.<|final|>"}, {"role": "user", "content": "Serializable transactions are expensive in our database. Can we replace them with a row lock on one doctor?"}, {"role": "assistant", "content": "<|reason|>A common lock point works only if every transaction that can affect the invariant participates in the same protocol, and the check occurs after acquiring it. Locking one arbitrarily selected row can fail if that row is deleted or bypassed.<|end_reason|><|answer|>Yes, if you introduce a stable guard row for the on-call group and require every schedule-changing transaction to lock it before reading the invariant, then re-read the relevant state and update within that transaction. Alternatively keep an explicit on-call count in the guard row and update it with a conditional predicate that forbids zero. Document the protocol and enforce it in one service/database boundary; a lock that some writer omits provides no guarantee. Continue to handle deadlocks/timeouts and retry transactions safely.<|final|>"}]}
34
+ {"messages": [{"role": "user", "content": "An API creates a payment and clients retry after timeouts. Design an idempotency mechanism that avoids both duplicate charges and falsely treating different requests as the same operation."}, {"role": "assistant", "content": "<|reason|>A stable client key identifies the logical operation, while a canonical payload hash detects accidental key reuse. Claiming that key, recording the payment intent, and storing the response must be atomic; the external processor needs its own idempotency key because a database cannot transact with it.<|end_reason|><|answer|>Scope an idempotency key by customer/account and endpoint, store its canonical request hash, operation ID, status, and response. A unique constraint allows only one claimant. Same key and same hash returns the existing status/result; same key with a different hash is a conflict. Create the local payment intent and outbox command in one database transaction, then call the provider with a stable provider idempotency key. Persist provider outcomes and make webhook handling idempotent. A timeout is an unknown outcome, not proof of failure; query/retry with the same provider key rather than creating a new charge.<|final|>"}, {"role": "user", "content": "The payment provider times out after it may have charged the card, and its idempotency key expires after 24 hours. What should retries do on day two?"}, {"role": "assistant", "content": "<|reason|>Blindly resending after the provider forgets the key can duplicate a charge. Preserve the local operation identity and reconcile the ambiguous result by querying provider records or using a merchant reference before issuing another charge.<|end_reason|><|answer|>After the provider’s deduplication window, do not automatically create a fresh charge for an unresolved operation. Search/query by the provider’s durable transaction ID or merchant reference, inspect settlement/webhook records, and route unresolved cases to reconciliation or manual review. If the provider offers no reliable lookup, the system cannot promise safe automatic retry after key expiry; surface an indeterminate status and use compensating refund procedures if a duplicate is discovered. Keep local idempotency records longer than the business retry horizon.<|final|>"}]}
35
+ {"messages": [{"role": "user", "content": "Design a password-reset flow resistant to enumeration, token theft, replay, and log leakage. State what is stored server-side and when a token is consumed."}, {"role": "assistant", "content": "<|reason|>Use a high-entropy single-use bearer token delivered out of band, store only a hash, expire it, and consume it atomically with the password change. Uniform responses and rate limits prevent account enumeration; secrets must not enter URLs that leak through logs or referrers without mitigations.<|end_reason|><|answer|>Return the same status and broadly similar timing whether or not an account exists. Rate-limit by account and network signals without making the response disclose existence. Generate at least 128 bits of cryptographic randomness, send it over the registered channel, and store only a keyed hash or secure hash plus user, expiry, and used state. On submission, atomically validate and consume the token while changing the password; revoke sessions or offer that policy explicitly. Use HTTPS, no third-party content on reset pages, a restrictive Referrer-Policy, and redact query strings from logs. Never email the new password.<|final|>"}, {"role": "user", "content": "The reset token is currently in a URL query string, and our CDN logs full URLs. Can we keep the link format?"}, {"role": "assistant", "content": "<|reason|>A bearer token in a query string can leak through CDN/application logs, browser history, analytics, and referrer headers. If the format cannot change immediately, redaction and page-level leakage controls reduce exposure but do not remove the risk.<|end_reason|><|answer|>Prefer a fragment-based token (`#token`) so browsers do not send it in the initial HTTP request; page JavaScript can exchange it for a short-lived server-side reset session, then remove the fragment with history replacement. If a query parameter must remain, immediately redact it at CDN and application layers, disable third-party scripts, set `Referrer-Policy: no-referrer`, avoid analytics on that page, and exchange it once for a short-lived session before redirecting to a clean URL. Rotate/revoke existing reset tokens exposed in logs and review retention/access to those logs.<|final|>"}]}
36
+ {"messages": [{"role": "user", "content": "Explain consistent hashing for distributing keys across N cache nodes, including virtual nodes, replica selection, and how much data moves when one node is added."}, {"role": "assistant", "content": "<|reason|>A ring maps both nodes and keys into one ordered hash space; a key belongs to the next node clockwise. Adding a node splits only the arc it claims, so under uniform hashing expected movement is about 1/(N+1), while virtual nodes reduce imbalance variance.<|end_reason|><|answer|>Hash each physical node to many virtual positions on a ring and assign a key to the first position clockwise. For replication factor R, continue clockwise until R distinct physical nodes are selected. On adding one equally weighted node, roughly 1/(N+1) of uniformly distributed keys move to it in expectation, rather than nearly all keys under modulo-N hashing. Virtual-node counts should reflect capacity for heterogeneous machines. A migration plan still needs dual reads/writes or a versioned cutover, monitoring, and failure handling; the hash function alone does not move data or guarantee replica durability.<|final|>"}]}
37
+ {"messages": [{"role": "user", "content": "Describe a circuit breaker for a service dependency. Include states, concurrent probes, and how timeouts relate to retries."}, {"role": "assistant", "content": "<|reason|>The breaker limits repeated calls to a failing dependency: closed permits traffic, open rejects quickly, and half-open permits a bounded probe set. Retries should be bounded by a request deadline and coordinated with the breaker to avoid amplifying outages.<|end_reason|><|answer|>Track failures over a rolling time/count window. In closed state, calls proceed; crossing a configured threshold opens the breaker for a cooldown. In open state, fail fast; after cooldown, half-open allows a small number of probes, closing on sustained success and reopening on failure. Use a single atomic state transition or lease so many replicas do not all flood the dependency at once. Set connection/read deadlines, cap retries with exponential backoff and jitter, and avoid retrying non-idempotent operations without an idempotency key. Expose open-state duration and probe outcomes as metrics.<|final|>"}, {"role": "user", "content": "We want to return cached stale data while the breaker is open. Does that make the dependency failure invisible?"}, {"role": "assistant", "content": "<|reason|>A fallback can preserve user-facing availability, but it changes freshness and must be observable. It should not accidentally convert a failed write into success, and stale age needs a product-defined upper bound.<|end_reason|><|answer|>Use stale cached data only for operations whose contract permits it, include or track the data’s age, and emit fallback metrics/alerts so the outage is not hidden. Do not acknowledge a write as committed merely because a stale-read fallback exists. Bound stale serving by a maximum age, and decide what to do when no cache entry exists. Keep breaker state independent from cache freshness: a healthy cache does not prove the origin is healthy, and a successful fallback should not count as a dependency success probe.<|final|>"}]}
38
+ {"messages": [{"role": "user", "content": "A team wants at-most-once job execution by setting a database flag before running a job. Explain the crash window and propose a robust job-processing design."}, {"role": "assistant", "content": "<|reason|>Mark-before-work avoids duplicate starts but loses work if the process crashes after marking. Mark-after-work permits duplicates after a crash. Durable leases, idempotent effects, and transactional completion records address these failure windows more honestly.<|end_reason|><|answer|>Store jobs durably with status, lease owner/expiry, attempt count, and idempotency key. Workers claim jobs atomically (for example, using a row lock with `SKIP LOCKED`), set a bounded lease, execute with heartbeats if needed, and mark completion. Expired leases become eligible for retry. Since a worker can crash after applying an effect but before recording completion, make effects idempotent or commit the effect and job completion in one database transaction. External side effects require provider idempotency or an outbox/saga. This yields at-least-once attempts and effectively-once business effects, not guaranteed one physical execution.<|final|>"}, {"role": "user", "content": "A job can run for longer than its lease, so a second worker may start it. What prevents the old worker from committing after losing ownership?"}, {"role": "assistant", "content": "<|reason|>Lease expiry alone cannot stop a paused process from resuming. A monotonically increasing fencing token must accompany writes, and the destination must reject tokens older than the latest accepted owner.<|end_reason|><|answer|>Increment a per-job fencing generation whenever a worker claims or renews ownership, and include it in every protected write. The resource receiving the write checks that the token is at least the latest accepted generation; an old worker with token 7 is rejected after token 8 has been issued. A lease without fencing only coordinates cooperative workers and is unsafe under pauses or network partitions. If the side effect is an external API, it must support idempotency or fencing for this guarantee to extend there.<|final|>"}]}
39
+ {"messages": [{"role": "user", "content": "A multiset of n items is shuffled uniformly. Derive the probability of at least one collision when n items are independently assigned to m equally likely bins, and give a useful approximation regime."}, {"role": "assistant", "content": "<|reason|>The complement event assigns all n items to distinct bins: there are m(m−1)…(m−n+1) assignments out of m^n when n≤m. The birthday approximation follows by expanding the log of this product when n is small relative to m.<|end_reason|><|answer|>For n≤m, `P(no collision)=(m)_n/m^n=product_{i=0}^{n-1}(1-i/m)`, so `P(at least one collision)=1-(m)_n/m^n`; for n>m it is 1 by the pigeonhole principle. When n is much smaller than m, `log P(no collision)=sum_i log(1-i/m)≈-n(n-1)/(2m)`, giving collision probability approximately `1-exp(-n(n-1)/(2m))`. The approximation is useful around n proportional to sqrt(m); it is not a substitute for the exact product when higher-order terms matter.<|final|>"}]}
40
+ {"messages": [{"role": "user", "content": "Count derangements of n objects, prove the inclusion-exclusion formula, and provide a recurrence useful for exact computation."}, {"role": "assistant", "content": "<|reason|>Let A_i be permutations fixing position i. Inclusion-exclusion over chosen fixed positions leaves `(n-k)!` permutations, giving the alternating sum. A recurrence follows by considering the image of the first position and whether the displaced object returns to it.<|end_reason|><|answer|>The number is `D_n=n! sum_{k=0}^n (-1)^k/k!`, with `D_0=1`. Inclusion-exclusion works because choosing a set of k fixed positions leaves `(n-k)!` permutations, and there are `C(n,k)` such sets. A stable integer recurrence is `D_1=0` and `D_n=(n-1)(D_{n-1}+D_{n-2})` for n≥2: choose the image of object 1 in n−1 ways, then split according to whether that chosen object maps back to 1. The probability a uniform permutation is a derangement is `D_n/n!`, tending to `1/e`; rounding `n!/e` gives the exact integer for n≥1.<|final|>"}]}
41
+ {"messages": [{"role": "user", "content": "Prove Cayley’s formula that the number of labeled trees on n vertices is n^(n−2), and explain the n=1 boundary case."}, {"role": "assistant", "content": "<|reason|>A Prüfer code bijects labeled trees on n vertices with sequences of length n−2 over the same label set. Every sequence decodes uniquely, and every tree encodes uniquely by repeatedly deleting its least-labeled leaf.<|end_reason|><|answer|>For n≥2, repeatedly remove the smallest-labeled leaf and record its neighbor until two vertices remain. This yields a length n−2 sequence, each entry chosen from n labels. Conversely, given the sequence, repeatedly connect the smallest label absent from the remaining sequence to its first entry, delete that entry, and finally connect the last two labels. The procedures are inverse, so there are n^(n−2) trees. For n=2 the empty code corresponds to one tree. For n=1 there is one tree; the expression `1^(−1)` is not the right way to derive that boundary, so define the count separately.<|final|>"}]}
42
+ {"messages": [{"role": "user", "content": "Find the expected number of draws to see every one of n equally likely coupon types, and derive the variance."}, {"role": "assistant", "content": "<|reason|>When k types have been seen, each draw finds a new type with probability `(n-k)/n`, so the waiting time for the next new type is geometric with that success probability. The waiting stages are independent by the memoryless property of independent draws.<|end_reason|><|answer|>Let `T_k` be the waiting time to move from k seen types to k+1. It is geometric with parameter `(n-k)/n`, so its mean is `n/(n-k)` and variance `(1-p)/p^2`. Summing means gives `E[T]=n H_n`. Summing variances gives `Var(T)=n^2 H_n^(2)-n H_n`, where `H_n=sum_{j=1}^n 1/j` and `H_n^(2)=sum 1/j^2`. The expected time grows as `n log n + gamma*n + O(1)`, explaining the long tail near completion. This assumes independent uniform draws; unequal coupon probabilities can increase the expectation substantially.<|final|>"}]}
43
+ {"messages": [{"role": "user", "content": "In n independent uniform assignments to m labeled boxes, derive the probability that exactly r boxes are empty. Include feasibility conditions and a normalization check."}, {"role": "assistant", "content": "<|reason|>Choose which r boxes are empty, then count surjections from n labeled balls onto the remaining m−r boxes. Inclusion-exclusion gives the surjection count, equivalently `(m-r)! S(n,m-r)`.<|end_reason|><|answer|>For `q=m-r`, the count is `C(m,r) * q! * S(n,q)`, so the probability is that quantity divided by `m^n`. Inclusion-exclusion writes the surjection count as `sum_{j=0}^q (-1)^j C(q,j)(q-j)^n`. The probability is zero unless `0<=r<=m` and `q<=n` (for n>0; the empty assignment has all m boxes empty when n=0). Summing over r yields `m^n`, since every assignment has exactly one number of empty boxes. For efficient computation, Stirling numbers satisfy `S(n,q)=q*S(n-1,q)+S(n-1,q-1)`.<|final|>"}]}
44
+ {"messages": [{"role": "user", "content": "Combine congruences x≡a (mod m) and x≡b (mod n) even when moduli are not coprime. State the exact solvability condition and construct one solution."}, {"role": "assistant", "content": "<|reason|>The residues must agree modulo the gcd. After dividing by g=gcd(m,n), the reduced moduli are coprime and a modular inverse solves for the offset; solutions repeat modulo lcm(m,n).<|end_reason|><|answer|>Let `g=gcd(m,n)`. A solution exists iff `a-b` is divisible by g. Write `m'=m/g`, `n'=n/g`; solve `m' t ≡ (b-a)/g (mod n')`, so `t=((b-a)/g)*(m')^{-1} mod n'` when `n'>1` (if n'=1, take t=0). Then `x=a+m*t` is a solution modulo `lcm(m,n)=m*n'`. Reduce x to the desired canonical residue. Extended Euclid computes g and the inverse in logarithmic time. For non-coprime moduli, blindly applying the coprime CRT formula is invalid.<|final|>"}]}
45
+ {"messages": [{"role": "user", "content": "Solve ax+by=c over integers and characterize all solutions, including zero coefficients. Explain the role of gcd and extended Euclid."}, {"role": "assistant", "content": "<|reason|>Integer combinations of a and b are exactly the multiples of g=gcd(a,b). Extended Euclid supplies one combination for g; scaling it yields a particular solution, and the homogeneous equation gives a one-parameter family.<|end_reason|><|answer|>If a=b=0, there are no solutions unless c=0, in which case every integer pair works. Otherwise let g=gcd(|a|,|b|); solutions exist iff g divides c. Find `u,v` with `au+bv=g`; then `(x0,y0)=(u*c/g,v*c/g)` is a particular solution. All solutions are `x=x0+(b/g)t`, `y=y0-(a/g)t` for integer t. Substitution verifies the equation, and dividing the difference of any two solutions by g shows this parameterization is complete. Extended Euclid runs in O(log max(|a|,|b|)).<|final|>"}]}
46
+ {"messages": [{"role": "user", "content": "For a finite absorbing Markov chain, compute the expected number of steps to absorption from each transient state. State the condition for the linear system to be valid."}, {"role": "assistant", "content": "<|reason|>The first-step equation is `t=1+Qt`, because one step is spent before transitioning among transient states. If absorption occurs with probability one from every transient state, the spectral radius of Q is below one and `(I-Q)` is invertible.<|end_reason|><|answer|>Partition the transition matrix into transient block Q and absorbing transitions. For each transient state i, `t_i=1+sum_j Q_ij t_j`; solve `(I-Q)t=1`. Absorption with probability one and finite expected absorption time ensures the fundamental matrix `N=(I-Q)^{-1}=I+Q+Q^2+...` exists, with `t=N1`. Use a numerically stable linear solver rather than explicitly forming the inverse. If a transient class can avoid absorption forever with positive probability, expected absorption time may be infinite and the finite solution interpretation fails. For exact rational transition probabilities, rational Gaussian elimination can provide exact results on small chains.<|final|>"}]}
47
+ {"messages": [{"role": "user", "content": "A diagnostic has prevalence p, sensitivity s, and specificity c. Derive the probability a positive result is a true positive and show why high accuracy alone can mislead."}, {"role": "assistant", "content": "<|reason|>Bayes’ rule compares true positives `p*s` with all positive outcomes, including false positives `(1-p)*(1-c)`. A low prevalence can make the false-positive term dominate even when specificity is high.<|end_reason|><|answer|>`P(disease | positive)=p*s/[p*s+(1-p)*(1-c)]`, assuming nonzero probability of a positive test. For example, at prevalence 1%, sensitivity 99%, and specificity 95%, the posterior is `0.0099/(0.0099+0.0495)≈16.7%`; most positives are false positives despite strong sensitivity. Always distinguish sensitivity/specificity from positive predictive value and report the population prevalence used. If the test characteristics vary by subgroup or selection affects who is tested, a single pooled calculation may be misleading.<|final|>"}]}
48
+ {"messages": [{"role": "user", "content": "For independent Bernoulli variables with total mean mu, state and interpret a Chernoff upper-tail bound for exceeding `(1+delta)mu`, delta>0. Give the assumptions and a simpler looser form."}, {"role": "assistant", "content": "<|reason|>Exponential Markov inequality applied to the moment-generating function yields the multiplicative Chernoff bound. Independence is essential for factoring the moment-generating function; the simpler `exp(-mu*delta^2/3)` bound holds for 0<delta<=1.<|end_reason|><|answer|>If X is a sum of independent Bernoulli variables with mean mu, then `P[X >= (1+delta)mu] <= [e^delta/(1+delta)^(1+delta)]^mu` for delta>0. For `0<delta<=1`, this is at most `exp(-mu*delta^2/3)`. The bound quantifies exponential concentration above the mean; it does not assert the exact tail probability. Use a threshold interpretation carefully when `(1+delta)mu` is nonintegral. For dependent indicators, a separate dependence condition or inequality is needed.<|final|>"}]}
49
+ {"messages": [{"role": "user", "content": "Use Jensen’s inequality to bound the average of a convex function, and characterize equality when the function is strictly convex. Explain how it can prove an extremum under a fixed-sum constraint."}, {"role": "assistant", "content": "<|reason|>Convexity places each function value above the tangent/chord average, so averaging inputs before applying f cannot exceed the average of f. Strict convexity forces equality only when all inputs coincide, subject to positive weights.<|end_reason|><|answer|>For weights `w_i>=0` summing to one and convex f, `f(sum_i w_i x_i) <= sum_i w_i f(x_i)`. If f is strictly convex and every weight is positive, equality holds exactly when all x_i are equal. Under a fixed arithmetic mean, this bounds the average of f from below; for concave f the inequality reverses and often gives a maximum at equal inputs. Jensen supplies a bound, not automatically the global solution—check domain constraints, equality feasibility, and whether the objective’s direction matches the inequality.<|final|>"}]}
50
+ {"messages": [{"role": "user", "content": "How many binary strings of length n are distinct up to cyclic rotation (necklaces), with reflections not identified? Derive the formula using Burnside’s lemma."}, {"role": "assistant", "content": "<|reason|>Burnside averages the number of strings fixed by each rotation. A rotation by k positions has gcd(n,k) cycles, so a fixed string chooses one bit per cycle; grouping rotations by their gcd yields the divisor sum.<|end_reason|><|answer|>The number is `N(n)=1/n * sum_{k=0}^{n-1} 2^{gcd(n,k)}`. Equivalently, `N(n)=1/n * sum_{d|n} phi(d)*2^(n/d)`, where phi is Euler’s totient. A rotation fixes a string iff bits are constant on each orbit of positions, giving `2^gcd(n,k)` fixed strings. Reflections are excluded; including them gives bracelets and requires the dihedral group’s reflection fixed-point counts. For n=1 the formula yields 2, the two one-bit necklaces.<|final|>"}]}
orion-extreme-reasoning-hard-expanded.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"messages": [{"role": "user", "content": "Design and implement an offline algorithm for dynamic connectivity in an undirected graph. The input is n and a sequence of operations add(u,v), remove(u,v), and connected(u,v); an edge may be added again after it has been removed, but duplicate active copies are forbidden, and every removal must refer to an active edge. Return one Boolean per connected query, in input order. Explain why a normal disjoint-set union structure is insufficient, give correctness and complexity arguments, and include executable tests for interval boundaries, repeated edge lifetimes, self-loops, and invalid operations."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: Connectivity is monotone only while edges are being added; a deletion can split a component, and ordinary DSU has no cheap inverse for a union. Since the complete operation sequence is known, convert each edge's active lifetime into a half-open interval [add_time, remove_time), or [add_time, Q) if it remains active. A segment tree over operation indices stores each edge in O(log Q) canonical nodes covering its lifetime. During a depth-first traversal, a rollback DSU contains exactly the edges stored at ancestors and the current node. At a query leaf, its connectivity answers therefore match the graph at that time. Use union by size but no path compression: every successful union records the changed child root and the previous parent size, so rollback is exact. Failed unions need no record because they change no state. Half-open intervals exclude the edge at its remove operation; leaves corresponding to add/remove operations are not queries, but this convention also makes the invariant unambiguous. Validate malformed operations and active-edge rules before traversal. Self-loops are valid and simply create no DSU change. With A edge lifetimes and Q operations, interval insertion creates O(A log Q) stored edges, each union/find costs O(log n) worst case, and traversal costs O(Q); total time is O((Q + A log Q) log n), with O(Q + A log Q + n) memory. The logarithmic DSU bound follows because union-by-size can increase a node's depth only when its component at least doubles; omitting path compression is essential to the simple rollback proof.<|end_reason|><|answer|>```python\nfrom typing import Iterable, List, Tuple\n\nOperation = Tuple[str, int, int]\n\n\ndef offline_connectivity(n: int, operations: Iterable[Operation]) -> List[bool]:\n \"\"\"Answer add/remove/connected operations on an undirected graph offline.\n\n Vertices are 0..n-1. Operations are 3-tuples such as\n (\"add\", u, v), (\"remove\", u, v), or (\"connected\", u, v).\n Parallel active copies of an undirected edge are rejected.\n \"\"\"\n if type(n) is not int or n <= 0:\n raise ValueError(\"n must be a positive integer\")\n ops = list(operations)\n q = len(ops)\n if q == 0:\n return []\n\n active = {} # normalized edge -> start time\n intervals = [] # (start, end, edge), with half-open time ranges\n for t, op in enumerate(ops):\n if not isinstance(op, (tuple, list)) or len(op) != 3:\n raise ValueError(f\"operation {t} must be a 3-item tuple/list\")\n kind, u, v = op\n if kind not in (\"add\", \"remove\", \"connected\"):\n raise ValueError(f\"unknown operation at index {t}: {kind!r}\")\n if type(u) is not int or type(v) is not int or not (0 <= u < n and 0 <= v < n):\n raise ValueError(f\"invalid vertex in operation {t}\")\n edge = (u, v) if u <= v else (v, u)\n if kind == \"add\":\n if edge in active:\n raise ValueError(f\"edge {edge} is already active\")\n active[edge] = t\n elif kind == \"remove\":\n if edge not in active:\n raise ValueError(f\"edge {edge} is not active\")\n intervals.append((active.pop(edge), t, edge))\n\n for edge, start in active.items():\n intervals.append((start, q, edge))\n\n tree = [[] for _ in range(4 * q)]\n\n def add_interval(node: int, left: int, right: int,\n ql: int, qr: int, edge: Tuple[int, int]) -> None:\n if ql >= right or qr <= left:\n return\n if ql <= left and right <= qr:\n tree[node].append(edge)\n return\n mid = (left + right) // 2\n add_interval(node * 2, left, mid, ql, qr, edge)\n add_interval(node * 2 + 1, mid, right, ql, qr, edge)\n\n for start, end, edge in intervals:\n if start < end:\n add_interval(1, 0, q, start, end, edge)\n\n parent = list(range(n))\n size = [1] * n\n history = [] # (child_root, parent_root, old_parent_size)\n\n def find(x: int) -> int:\n while parent[x] != x: # deliberately no path compression\n x = parent[x]\n return x\n\n def union(a: int, b: int) -> None:\n ra, rb = find(a), find(b)\n if ra == rb:\n return\n if size[ra] < size[rb]:\n ra, rb = rb, ra\n history.append((rb, ra, size[ra]))\n parent[rb] = ra\n size[ra] += size[rb]\n\n def rollback(snapshot: int) -> None:\n while len(history) > snapshot:\n child, root, old_size = history.pop()\n parent[child] = child\n size[root] = old_size\n\n answers = []\n\n def visit(node: int, left: int, right: int) -> None:\n snapshot = len(history)\n for u, v in tree[node]:\n union(u, v)\n if right - left == 1:\n kind, u, v = ops[left]\n if kind == \"connected\":\n answers.append(find(u) == find(v))\n else:\n mid = (left + right) // 2\n visit(node * 2, left, mid)\n visit(node * 2 + 1, mid, right)\n rollback(snapshot)\n\n visit(1, 0, q)\n return answers\n\n\nif __name__ == \"__main__\":\n # Boundary, repeated lifetime, connectivity split, and self-loop checks.\n ops = [\n (\"add\", 0, 1), (\"connected\", 0, 1),\n (\"add\", 1, 2), (\"connected\", 0, 2),\n (\"remove\", 1, 2), (\"connected\", 0, 2),\n (\"add\", 1, 2), (\"connected\", 0, 2),\n (\"add\", 3, 3), (\"connected\", 0, 3), (\"connected\", 3, 3),\n (\"remove\", 3, 3), (\"connected\", 0, 3), (\"connected\", 3, 3),\n ]\n assert offline_connectivity(4, ops) == [True, True, False, True, False, True, False, True]\n assert offline_connectivity(2, []) == []\n for bad in [\n [(\"remove\", 0, 1)],\n [(\"add\", 0, 1), (\"add\", 1, 0)],\n [(\"add\", 0, 2)],\n [(\"wat\", 0, 0)],\n [(\"add\", 0)],\n ]:\n try:\n offline_connectivity(2, bad)\n except ValueError:\n pass\n else:\n raise AssertionError(f\"invalid input was accepted: {bad!r}\")\n print(\"all offline-connectivity tests passed\")\n```\n\nThe API intentionally treats undirected edges as normalized endpoint pairs. A removed edge is absent beginning at its removal index; edge intervals are half-open. Queries at any later index observe the resulting graph. The validation pass ensures malformed histories fail before any answers are returned. This implementation is offline: it cannot emit answers before the operation sequence is complete.\n\n### Correctness argument and audit details\n\nTreat each operation index as a time point in `[0,Q)`. For an undirected edge e, the input validation pass gives a single active interval `[l_e,r_e)`: `l_e` is its add index, and `r_e` is the remove index or Q if it is never removed. The half-open convention means an edge is present at every later query before its removal, and absent at the removal index. Since one operation occupies each index, a query cannot coincide with an add or removal; using a consistent convention still prevents off-by-one ambiguity.\n\nA segment tree node represents an interval of time. The canonical range-decomposition procedure stores e in disjoint tree nodes whose intervals partition `[l_e,r_e)`. Thus for any leaf t, exactly one stored copy of e occurs among the leaf’s ancestors if and only if `l_e <= t < r_e`. During a DFS, all ancestor edge lists have been unioned before visiting t, and no edge outside those lists has been unioned. Therefore the DSU’s equivalence classes at a query leaf are exactly the connected components of the graph at time t. A connected query is correct if `find(u)==find(v)`.\n\nThe rollback invariant is that `history` contains one record for each successful union since the current DFS ancestor state. A successful union changes one root’s parent and the other root’s size, so storing `(child_root,parent_root,old_parent_size)` is sufficient to invert it. Union by size ensures the attached root was a root before the change. Reverse-order rollback restores nested unions in the reverse order they were applied, so at the return from a node the DSU equals the state at entry. A failed union changes no field and needs no history record. Path compression is deliberately omitted: compression would mutate parent pointers during `find`, and every such mutation would also need to be logged.\n\n### Complexity and operational limits\n\nEach edge lifetime is decomposed into O(log Q) canonical nodes, so the tree stores O(A log Q) edge copies for A lifetimes. DFS visits O(Q) segment-tree nodes. Each stored copy triggers at most one union; a union/find is O(log n) worst case under union by size without compression. The resulting bound is O((Q + A log Q) log n) time and O(n + Q + A log Q) memory. The recursion depth is O(log Q) for range insertion and O(log Q) for traversal. The implementation is offline: it needs the full operation sequence before returning any answer, and memory grows with the sequence.\n\nThe implementation normalizes `(u,v)` to `(min(u,v),max(u,v))`, so adding `(u,v)` and later removing `(v,u)` refers to the same undirected edge. It intentionally rejects adding that edge twice while active; if parallel edges with independent identities are desired, the input must carry edge IDs and each ID needs its own lifetime. Self-loops are legal but never join two DSU components. Isolated vertices are connected to themselves, so `connected(v,v)` is true even without edges.\n\nA useful independent test strategy is to generate short valid histories, maintain a plain active-edge set, and answer each query by rebuilding adjacency and running BFS. Comparing that oracle against this implementation catches interval endpoint and rollback bugs. The batch was checked on seeded random histories in addition to the embedded deterministic tests. Particularly valuable cases are add/query/remove/query on one edge; removing one edge while another alternate path remains; a self-loop; re-adding a removed edge; reversed endpoint order; a query whose endpoints are identical; and invalid remove/duplicate add operations. The segment-tree method does not require an explicit bridge or component-split operation: deleting an edge simply means it is absent at leaves after its lifetime.<|final|>"}]}
2
+ {"messages": [{"role": "user", "content": "We need a reliable event-driven service. An API request changes our database and must eventually publish an event to a broker; consumers update their own databases. Network failures can happen at any point. Explain a design that avoids lost events and duplicate business effects, and be precise about what ‘exactly once’ can and cannot mean."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: The unsafe design commits the business row and then publishes: a crash between those actions loses the event. Reversing the order can publish an event for a transaction that later rolls back. A database transaction cannot normally atomically commit with an independent broker, so the dependable boundary is the service database itself. Persist the business change and an outbox record in one local transaction, then relay the outbox at least once. A relay crash after broker acceptance but before recording success causes redelivery, so delivery is not exactly once. Make the effect idempotent instead: consumers insert a unique event ID into an inbox and apply their local business update in the same transaction. If either transaction rolls back, both inbox claim and effect roll back; if it commits, a duplicate cannot reapply the effect. This provides effectively-once state transition for a defined database scope, not magical exactly-once transport across arbitrary systems. External side effects require their own idempotency contract or a compensating workflow.<|end_reason|><|answer|>Use a **transactional outbox + idempotent consumer** pattern.\n\n1. **API transaction:** Validate the request and, in one database transaction, write the business state and an outbox row containing a stable event ID, event type, payload, creation time, and (if ordering matters) aggregate ID and sequence. A unique client idempotency key should also be stored with a request-payload hash and the eventual response. Repeating the same key and same payload returns the stored result; reusing it with a different payload is a conflict. This handles the case where the API committed but its response was lost.\n2. **Outbox relay:** A worker reads unpublished rows, publishes them, waits for broker acknowledgement, and only then marks them published. It must not mark first: a crash after marking but before sending would lose the event. A crash after sending but before marking may resend it; that is expected. Multiple workers can claim rows with database locking (for example, `FOR UPDATE SKIP LOCKED`), subject to the ordering policy described below.\n3. **Consumer transaction:** On receipt, begin a transaction in the consumer database. Insert `(consumer_name, event_id)` into an inbox table with a unique constraint, apply the local state change, and commit both together. If the insert conflicts, the event has already been applied and can be acknowledged without repeating the effect. If applying the effect fails, roll back the inbox insert too, allowing safe retry. Acknowledge the broker only after commit.\n\nThe guarantee is **at-least-once delivery plus deduplicated, atomic local effects**. It is often called effectively-once processing for a particular consumer database. It is not a guarantee that a network message is physically delivered once. If a consumer calls a payment gateway, sends email, or writes to another independent database, its local inbox transaction cannot atomically cover that external action. Use the external provider's idempotency key, a second outbox, or a saga with explicit compensation and reconciliation. Monitor the age/count of unpublished outbox rows, consumer lag, and repeated failures; define retention long enough that old broker redeliveries still encounter deduplication records.\n\n### Failure boundaries and idempotency semantics\n\nThe central atomicity boundary is the service’s relational database. It can atomically commit a business-state transition and an outbox row because both are rows in the same transaction. It cannot atomically commit that transaction together with a broker publish unless both systems participate in a genuine distributed transaction protocol, which is often unavailable or undesirable. The outbox therefore converts an impossible cross-system atomic commit into a durable local fact plus retryable delivery.\n\nThe API idempotency key protects a different uncertainty boundary: the server may commit and then lose its response. The key must identify a logical command, not a network attempt. Scope it by caller and operation, bind it to a canonical payload hash, and persist the resulting operation/response in the same transaction as the transfer. A matching retry returns the prior result. A mismatching payload under the same key is a conflict, not a new transfer. Retain keys for at least the documented retry horizon; deleting them too early reopens the duplicate-command risk.\n\nFor the consumer, the inbox insert and projection update must be one transaction. If the consumer writes the inbox marker first and crashes before the balance update, a retry can be incorrectly suppressed. If it updates the balance first and crashes before the marker, a retry can apply the delta twice. Atomic commit removes both failure windows. The broker acknowledgement follows the local commit, never precedes it. An acknowledgement lost after commit is harmless because the redelivered event hits the inbox uniqueness constraint.<|final|>"}, {"role": "user", "content": "Make this concrete for money transfers between two accounts. We require no overdrafts, idempotent API retries, and strict per-account event order. A consumer must update a balance projection. The relay can run on many workers, and a transfer emits a debit and a credit."}, {"role": "assistant", "content": "<|reason|>Auditable solution rationale: The transfer's debit, credit, idempotency record, and two account-specific outbox rows must share one database commit; otherwise partial transfers or missing notifications are possible. Lock both account rows in deterministic account-ID order to avoid deadlocks, validate the source balance while locked, update balances, and increment each account's own monotonic version. Emit one event per account with that account's version and a common transfer ID. Partitioning by account preserves broker ordering only if the relay also prevents concurrent sends for the same account; a broker partition key alone cannot repair two workers publishing version 12 before version 11. Consumers should deduplicate by event ID and apply only the expected account version. A later version arriving early must be buffered/retried, not marked as fully applied. The two account events need not arrive atomically; if a downstream consumer requires an atomic cross-account view, it needs a transfer-level coordination rule, not merely per-account ordering.<|end_reason|><|answer|>A concrete relational design can use these logical tables:\n\n```sql\nCREATE TABLE api_requests (\n idempotency_key TEXT PRIMARY KEY,\n request_hash TEXT NOT NULL,\n transfer_id UUID NOT NULL UNIQUE,\n response_json JSONB NOT NULL\n);\n\nCREATE TABLE accounts (\n account_id BIGINT PRIMARY KEY,\n balance_minor BIGINT NOT NULL CHECK (balance_minor >= 0),\n version BIGINT NOT NULL DEFAULT 0\n);\n\nCREATE TABLE transfers (\n transfer_id UUID PRIMARY KEY,\n source_id BIGINT NOT NULL,\n destination_id BIGINT NOT NULL,\n amount_minor BIGINT NOT NULL CHECK (amount_minor > 0)\n);\n\nCREATE TABLE outbox (\n event_id UUID PRIMARY KEY,\n aggregate_id BIGINT NOT NULL, -- account ID\n aggregate_version BIGINT NOT NULL,\n transfer_id UUID NOT NULL,\n event_type TEXT NOT NULL,\n payload JSONB NOT NULL,\n published_at TIMESTAMPTZ,\n UNIQUE (aggregate_id, aggregate_version)\n);\n\nCREATE TABLE inbox (\n consumer_name TEXT NOT NULL,\n event_id UUID NOT NULL,\n aggregate_id BIGINT NOT NULL,\n aggregate_version BIGINT NOT NULL,\n PRIMARY KEY (consumer_name, event_id),\n UNIQUE (consumer_name, aggregate_id, aggregate_version)\n);\n```\n\nFor each API request, calculate a canonical request hash and enter a transaction. First claim the idempotency key. If it already exists with the same hash, return its recorded response; if the hash differs, reject the request rather than silently treating a different transfer as a retry. For a new request, lock both account rows in ascending `account_id` order, even though only the source is debited. Check account existence, amount bounds, and `source.balance >= amount`; then insert the transfer, debit/credit the two balances, increment each account version, and insert one outbox event for each account using the returned version. Persist the response and idempotency record in the same transaction. Any error, including insufficient funds, rolls everything back. Use integer minor units (cents), not binary floating point.\n\nThe common `transfer_id` ties the debit and credit events together; each event also carries its account ID, account version, signed delta, and resulting balance or enough data to compute it. Make transfer and ledger constraints unique by transfer/account/leg so accidental duplicate application is detectable. Ordered row locking prevents opposing transfers from deadlocking due to inconsistent lock order. The database transaction serializes concurrent debits against the same account, so two requests cannot both pass a stale balance check and overdraw it.\n\nFor strict per-account order, route each outbox event with `aggregate_id` as the broker partition key, and assign versions while holding the account lock. The relay must serialize publication per account: it may have many workers globally, but it must not allow two workers to publish versions `v` and `v+1` for the same account concurrently. One option is a leased per-account relay cursor/lock and selection of the lowest unpublished version; publish, wait for acknowledgement, then advance. Do not rely on `SKIP LOCKED` by itself to preserve order, because another worker could skip a locked version and publish a later one. If a publish outcome is uncertain, retry the same event ID and version before advancing. Broker partition ordering then preserves accepted order for that account. If the broker or relay can still expose gaps, the consumer version check detects them.\n\nThe balance-projection consumer keeps a per-account applied version. In one local transaction it checks the inbox uniqueness key and expected version. If `event.version == current_version + 1`, it applies the delta, records the inbox event, and advances the version atomically. If the version is at most current, it is a duplicate/stale delivery and can be acknowledged after confirming the dedupe record or projection state. If it is greater than `current_version + 1`, do not mark it applied: buffer it or retry until the gap is filled, and alert on a persistent gap. Commit before broker acknowledgement. The two account events may be observed at different times, so consumers requiring an atomic view of both sides must additionally wait for both legs of a transfer (or consume a transaction-level event into a suitably coordinated projection). Per-account ordering alone does not promise cross-account simultaneity.\n\nTest crash points explicitly: API response loss after commit must replay the same response; relay crash before send must leave a retryable row; crash after broker acknowledgement but before `published_at` must produce a harmless duplicate; consumer crash before commit must leave no inbox/effect; consumer crash after commit but before acknowledgement must be deduplicated. Also test simultaneous transfers from one source account, opposite-direction transfers, same idempotency key with changed payload, and out-of-order versions. This design prevents lost committed events and duplicate local balance effects, while honestly retaining at-least-once transport semantics.\n\n### Transaction sequence and invariants\n\nA robust transfer transaction has the following logical order:\n\n1. Canonicalize and validate the request (positive integer minor-unit amount, distinct source/destination IDs, accepted currency, and idempotency key).\n2. Claim or read the idempotency record. If an existing row has a different hash, reject. If it matches, return the recorded transfer/result. A uniqueness race between simultaneous requests is resolved by the database constraint; the loser rereads the committed row.\n3. Lock both account rows in ascending account-ID order. Sorting lock acquisition avoids the classic deadlock where transfer A→B locks A then B while transfer B→A locks B then A.\n4. Revalidate account status and source balance while locks are held. Debit and credit in integer minor units, increment each account’s version, insert the transfer/ledger rows, and insert one account event for each affected account using the version returned by that update.\n5. Store the API response/idempotency result and commit all rows together.\n\nThe invariant is that the source debit and destination credit either both commit or neither commits. Database checks such as `balance_minor >= 0`, a positive-amount constraint, unique transfer/leg keys, and unique `(account_id,version)` events are useful defense in depth. A same-account transfer should be rejected or explicitly defined as a no-op; otherwise a single row may be updated twice and the two per-account event versions are ambiguous. If account currency can differ, conversion and rounding rules must be explicit rather than hidden in floating-point arithmetic.\n\n### Ordering and relay concurrency\n\nA version is assigned while its account row is locked, giving a total order for events affecting that account. The outbox event should include account ID, account version, event ID, transfer ID, and an immutable delta or resulting balance. A relay can run many workers across accounts, but at most one publication for a given account may be in flight if strict order is required. A common strategy is a per-account relay cursor/lease that selects the lowest unpublished sequence, publishes it, waits for broker acknowledgement, and only then advances. `SKIP LOCKED` alone is not an ordering guarantee: a second worker could skip a locked version v and send v+1 first.\n\nUse account ID as the broker partition key so accepted events for one account share an ordered partition. Broker ordering does not fix concurrent producer races before enqueue, so the relay serialization is still necessary. If a producer times out after the broker may have accepted an event, retry the same event ID and version before publishing the next version. Consumers can detect a gap if they receive v+1 while expecting v; they should buffer/retry rather than mark v+1 as applied.\n\nTwo per-account events for one transfer are not an atomic cross-account message. A projection that needs both sides simultaneously must use a transfer-level completion barrier, wait for both correlated legs, or consume a single transaction event with its own consistency model. Per-account ordering promises no cross-account simultaneity.\n\n### Failure-injection matrix\n\n| Failure point | Required outcome |\n|---|---|\n| API dies before transaction commit | No transfer, no idempotency success, no outbox event; retry may create it. |\n| Commit succeeds but HTTP response is lost | Same key/hash returns the committed result; no second debit. |\n| Relay dies before broker send | Outbox row remains retryable. |\n| Broker accepts send but relay dies before recording acknowledgement | Same event may be delivered twice; inbox deduplication prevents a second effect. |\n| Consumer dies before local commit | Neither inbox claim nor projection update persists; redelivery retries both. |\n| Consumer commits but acknowledgement is lost | Redelivery finds the inbox row and performs no second balance update. |\n| A later account version arrives before a missing version | Do not advance the projection; record a gap and recover/retry. |\n\nOperationally, alert on oldest unpublished event age, outbox backlog, repeated publish failures, consumer lag, version gaps, idempotency hash conflicts, and reconciliation differences between ledger and projection. The guarantee remains at-least-once transport plus effectively-once local database effects; it is not exactly-once execution of arbitrary external side effects.<|final|>"}]}
3
+ {"messages": [{"role": "user", "content": "For a flow network with integer costs that may be negative but has no negative-cost cycle reachable in the usable residual network, describe successive shortest augmenting path with potentials. Explain why raw Dijkstra is not initially valid."}, {"role": "assistant", "content": "<|reason|>Reduced costs `c(u,v)+p[u]-p[v]` become nonnegative when potentials are feasible. Dijkstra can then find a shortest residual augmenting path; updating potentials by the reduced distances preserves feasibility for future iterations.<|end_reason|><|answer|>Initialize feasible vertex potentials using Bellman–Ford when negative residual costs are present, or use zero potentials if all usable costs are nonnegative. On each iteration run Dijkstra on positive-capacity residual edges with reduced cost `c+p[u]-p[v]`; update potentials for reached vertices by their reduced distances. Trace the predecessor path, augment by the minimum residual capacity on it, and add `flow * original_path_cost` to total cost. Stop when the sink is unreachable or required flow is sent. This algorithm needs no reachable negative-cost residual cycle for the chosen optimization model; if such a cycle exists, first define whether circulation improvements are allowed and handle cycle cancellation/min-cost circulation appropriately. Complexity is O(F E log V) for unit augmentations and can depend on the number of augmentations; capacity scaling or cost-scaling methods may be preferable for large capacities.\n\n### Model, residual graph, and potential invariant\n\nAssume a directed network with capacities `cap(e) >= 0`, integral costs `cost(e)`, a source s, sink t, and a requested flow value F (or the goal of sending as much as possible at minimum cost). A residual edge describes how much additional flow can be sent. For every original edge u→v of capacity c and cost w, store a forward residual edge with remaining capacity c and cost w, and a reverse edge with remaining capacity zero and cost −w. Sending x units decreases forward capacity by x and increases reverse capacity by x. The reverse edge is not merely bookkeeping: it permits a later augmenting path to undo an earlier routing choice and reroute flow.\n\nDijkstra requires nonnegative edge lengths, but original costs may be negative. Assign a potential p(v) to each vertex and define reduced cost `c_p(u,v)=c(u,v)+p(u)-p(v)`. For any path P from s to v, the potential terms telescope, so `reduced_cost(P)=original_cost(P)+p(s)-p(v)`. Since the last two terms depend only on endpoints, shortest paths under reduced costs are the same paths as shortest paths under original costs. Potentials are therefore a reweighting, not a change to which route is optimal.\n\nA potential is feasible on the relevant residual graph when every positive-capacity edge has nonnegative reduced cost. Initially, if all usable costs are nonnegative, set all potentials to zero. If negative edges exist, run Bellman–Ford from s on positive-capacity residual edges and set p(v) to the shortest distance for each reachable vertex; unreachable vertices can be left unchanged. The absence of a reachable negative-cost cycle is required for finite shortest distances and feasible potentials. If the optimization model allows arbitrary circulations, a negative-cost cycle—even one disconnected from s—can lower total cost without changing s-to-t flow value. In that model, detect/cancel such cycles or use a min-cost-circulation algorithm; the simple source-to-sink augmentation method assumes no beneficial residual circulation outside the reachable augmentation problem.\n\n### One augmentation and why feasibility is preserved\n\nRun Dijkstra from s using reduced costs. Let d(v) be the resulting reduced shortest distance for each reached v. For each reached vertex update `p(v) <- p(v)+d(v)`. For every residual edge u→v whose endpoints are reached, shortest-path optimality gives `d(v) <= d(u)+c_p(u,v)`, hence the new reduced cost is\n\n`c_p'(u,v) = c_p(u,v)+d(u)-d(v) >= 0`.\n\nThus all reached residual edges remain nonnegative. Edges made newly available by augmentation are reverse edges of the selected shortest path. Every path edge is tight (`d(v)=d(u)+c_p(u,v)`), so its newly enabled reverse edge has reduced cost zero. Consequently the next Dijkstra iteration again sees nonnegative reduced costs on the source-reachable residual network. This invariant is the reason Dijkstra can be safely reused after each augmentation despite negative reverse costs in the original graph.\n\nIf t is unreachable, no residual s-to-t path remains, so the current flow is maximum. Otherwise, follow predecessor edges from t to s and compute the bottleneck `x=min residual_capacity` along the path, additionally capped by remaining requested flow. Augment x units, update paired residual capacities, and add `x * sum(original_cost(edge))` to the total cost. Summing original edge costs on the chosen path avoids sign mistakes in the reduced-distance conversion. If a target F was requested, stop when total flow reaches F; if the sink becomes unreachable first, the requested amount is infeasible.\n\n### Pseudocode outline\n\n```text\nbuild forward/reverse residual edge pairs\nif any usable initial cost is negative:\n p = BellmanFordDistancesFrom(s)\nelse:\n p[v] = 0\nflow = cost_total = 0\nwhile flow < F:\n d[*] = infinity; d[s] = 0\n run Dijkstra on positive-capacity edges with cost + p[u] - p[v]\n if d[t] is infinity: break\n for every reached v: p[v] += d[v]\n path = predecessor chain from t to s\n x = min(F-flow, residual capacity on path)\n update forward/reverse residual capacities along path\n flow += x\n cost_total += x * sum(original edge costs on path)\n```\n\nUse a sufficiently wide integer type for distances and `flow*cost`; sentinel infinity must not overflow when adding an edge cost. Do not relax zero-capacity edges. Store reverse-edge indices rather than searching for a matching endpoint, because parallel edges may have different costs/capacities. With integral capacities, augmentations are integral. Each shortest-path pass costs O(E log V) with a binary heap; initialization costs O(VE) if Bellman–Ford is needed. If each augmentation sends at least one unit and total flow is F, a simple bound is O(VE + F E log V). The number of augmentations can be large, so cost-scaling or capacity-scaling algorithms may be preferable for huge F.\n\n### Small verification example and limits\n\nSuppose the only two s-to-t routes are `s→a→t` with costs −2 and 5, and `s→t` with cost 4, each capacity one. Bellman–Ford finds a feasible initial potential despite the negative edge; Dijkstra on reduced costs selects the original cost-3 route through a, not the cost-4 direct edge. After that augmentation, reverse residual edges allow rerouting if a later unit can improve the total. Check the implementation on this case, on a network with parallel arcs, on zero-cost edges, on a requested flow exceeding capacity, and on an edge whose reverse becomes usable after augmentation. If a reachable negative cycle exists, the assumed shortest-path problem is ill-defined for walks and the method must not silently proceed.\"<|final|>"}]}
4
+ {"messages": [{"role": "user", "content": "Reduce a 2-SAT formula to graph reachability, test satisfiability, and explain what information SCCs provide. A clause has at most two literals."}, {"role": "assistant", "content": "<|reason|>Each clause `(a OR b)` is equivalent to implications `not a -> b` and `not b -> a`. If a literal and its negation share an SCC, each implies the other and neither truth assignment is possible. Otherwise the condensation ordering yields a satisfying assignment.<|end_reason|><|answer|>Create two vertices per variable, one for each literal. For `(a OR b)`, add edges `¬a -> b` and `¬b -> a`. Compute SCCs. The formula is unsatisfiable iff some variable’s two literal vertices lie in the same SCC. Otherwise topologically order the SCC condensation and set each variable true exactly when its positive-literal SCC occurs later than its negative-literal SCC in that order. Complementary implication edges guarantee this assignment respects every implication; verify all clauses as a defensive check. Tarjan or Kosaraju gives O(V+E) time and space, linear in formula size. For unit clause `(a)`, add `¬a -> a`. Preserve a clear literal-indexing convention; swapped positive/negative indices are a common source of incorrect assignments.\n\n### Literal graph construction\n\nRepresent variable x_i by two vertices, one for x_i and one for ¬x_i; choose and document a stable index mapping such as `pos(i)=2i`, `neg(i)=2i+1`. A clause `(a OR b)` is false only when both a and b are false. Equivalently, if a is false then b must be true, and if b is false then a must be true. Add implications `¬a -> b` and `¬b -> a`. A unit clause `(a)` can be represented as `(a OR a)`, producing `¬a -> a`. A tautology such as `(x OR ¬x)` adds self-implications and imposes no restriction.\n\nAn implication edge means truth propagates: if its source literal is true, its destination must be true. Every edge `u -> v` has a contrapositive edge `¬v -> ¬u` because both arise from the same clause. This complement symmetry is essential to the assignment theorem.\n\n### Why SCC equality detects impossibility\n\nIf x and ¬x belong to the same strongly connected component, there is a path x→¬x and a path ¬x→x. Assigning x true forces ¬x true; assigning x false means ¬x true and forces x true. Either truth value contradicts its complement, so the formula is unsatisfiable. Conversely, if no variable shares an SCC with its negation, the condensation graph is a DAG and a satisfying assignment can be constructed from a topological order.\n\nLet `rank(C)` be a topological position increasing along every condensation edge. Set x true exactly when `rank(comp(x)) > rank(comp(¬x))`; otherwise set x false. To verify implication closure, suppose an implication a→b had a true premise and false conclusion. Truth of a gives `rank(a)>rank(¬a)`, while falsity of b gives `rank(b)<rank(¬b)`. The implication and its contrapositive require `rank(a)<rank(b)` and `rank(¬b)<rank(¬a)`. Combining them yields the impossible strict cycle\n\n`rank(¬b) < rank(¬a) < rank(a) < rank(b) < rank(¬b)`.\n\nThus no implication can take a true literal to a false literal. Since each clause contributes its two implications, every clause is satisfied. This also explains why an arbitrary component numbering is not enough: the numbering must be a valid topological order, with the convention for increasing rank used consistently.\n\n### SCC algorithm and complexity\n\nUse Tarjan or Kosaraju on the implication graph. The graph has 2n vertices and at most 2m edges for m binary clauses, so SCC computation and construction take O(n+m) time and memory. Build the condensation edges (deduplicating is optional), topologically sort its components with Kahn’s algorithm, and apply the rank rule above. Verify the resulting assignment against the input clauses in O(n+m); this inexpensive check catches literal-index and order-direction bugs.\n\nFor Kosaraju, run DFS on the implication graph to obtain finish order, then DFS on the transpose in reverse finish order to label SCCs. Be careful not to confuse that SCC extraction order with the topological rank convention used in the assignment formula. Some implementations number SCCs in reverse topological order, so their comparison sign is the opposite. Rather than memorizing a `<` or `>` from a different implementation, explicitly construct or document the condensation topological order and test the rank rule.\n\n### Boundary tests\n\n- No clauses: satisfiable; every assignment is valid.\n- Unit clause x: edge ¬x→x; the rank rule must select x=true.\n- Unit clauses x and ¬x: both directions force one SCC; unsatisfiable.\n- Clause `(x OR ¬x)`: satisfiable for either value.\n- Implication chain `x→y`, `y→z`, plus unit x and unit ¬z: unsatisfiable, detected by the resulting forced path/contradiction.\n\nIf a formula includes an empty clause, it is immediately unsatisfiable; it is not represented by the at-most-two-literal construction unless handled separately. 2-SAT’s linear-time solution is special to clauses of size at most two; the analogous general 3-SAT problem is NP-complete.\"<|final|>"}]}
5
+ {"messages": [{"role": "user", "content": "For a finite absorbing Markov chain, compute the expected number of steps to absorption from each transient state. State the condition for the linear system to be valid."}, {"role": "assistant", "content": "<|reason|>The first-step equation is `t=1+Qt`, because one step is spent before transitioning among transient states. If absorption occurs with probability one from every transient state, the spectral radius of Q is below one and `(I-Q)` is invertible.<|end_reason|><|answer|>Partition the transition matrix into transient block Q and absorbing transitions. For each transient state i, `t_i=1+sum_j Q_ij t_j`; solve `(I-Q)t=1`. Absorption with probability one and finite expected absorption time ensures the fundamental matrix `N=(I-Q)^{-1}=I+Q+Q^2+...` exists, with `t=N1`. Use a numerically stable linear solver rather than explicitly forming the inverse. If a transient class can avoid absorption forever with positive probability, expected absorption time may be infinite and the finite solution interpretation fails. For exact rational transition probabilities, rational Gaussian elimination can provide exact results on small chains.\n\n### State partition and first-step derivation\n\nOrder the states so transient states come first and absorbing states last. The transition matrix has block form\n\n`P = [[Q, R], [0, I]]`,\n\nwhere Q contains transitions among transient states and R contains transitions from transient to absorbing states. Let t_i be the expected number of transitions until first entering an absorbing state, starting from transient state i. Condition on the first step: one step is always taken; with probability Q_ij the process then continues from transient state j; transitions represented in R absorb immediately and contribute no additional steps. Therefore\n\n`t_i = 1 + sum_j Q_ij t_j`.\n\nIn vector notation, `t = 1 + Q t`, hence `(I-Q)t=1`. This is a linear system, not a reason to explicitly compute a matrix inverse. Solve it using LU/Gaussian elimination for a small dense chain, or sparse iterative/factorization methods for a large sparse chain.\n\nThe fundamental matrix is `N=(I-Q)^(-1)=I+Q+Q^2+...` when the spectral radius of Q is less than one. The entry `(i,j)` is the expected number of visits to transient state j when starting from transient state i, including the initial visit when i=j. Summing a row gives expected total transient visits, which equals the expected number of steps before absorption. For a finite chain in which absorption occurs almost surely from every transient state, the expected time is finite and this series converges. If there is a closed nonabsorbing class reachable with positive probability, some expected absorption times are infinite and the stated finite-system interpretation fails.\n\n### Worked two-state example\n\nSuppose there are transient states A and B and one absorbing state. From A, transition probabilities are 1/2 to A, 1/4 to B, and 1/4 to absorption. From B, probabilities are 1/3 to A, 1/3 to B, and 1/3 to absorption. Then\n\n`Q = [[1/2, 1/4], [1/3, 1/3]]`.\n\nThe first-step equations are `t_A = 1 + t_A/2 + t_B/4` and `t_B = 1 + t_A/3 + t_B/3`. Rearranging gives `2t_A - t_B = 4` and `-t_A + 2t_B = 3`. Solving yields `t_A=11/3` and `t_B=10/3` steps. A useful check is to substitute both values back into the original equations; each right side must equal the corresponding expected time. The fractional answer is normal: an expectation need not be an integer.\n\n### Absorption probabilities and multiple absorbing states\n\nExpected duration is only one quantity. If there are k absorbing outcomes, let B be the matrix of absorption probabilities, one column per absorbing state. First-step conditioning gives `B=Q B + R`, so `(I-Q)B=R`. The same factorization of `I-Q` can solve both the expected-time vector and all absorption-probability columns. Each row of B should sum to one when eventual absorption is certain. This is a strong validation check and can reveal omitted transitions or a misordered state partition.\n\nFor a nontrivial starting distribution alpha over transient states, the expected time is `alpha^T t`; expected visits by state are `alpha^T N`. If an initial distribution already places mass on absorbing states, those starting states contribute zero additional steps.\n\n### Numerical and modeling checks\n\nBefore solving, verify each transition row sums to one (within a stated tolerance), entries are nonnegative, and the absorbing states really have self-transition probability one. Identify closed communicating classes in Q or otherwise establish that absorption is almost sure. A matrix can be nearly absorbing without being truly absorbing: then the expected time may be extremely large and `I-Q` can be ill-conditioned. Use a stable linear solver, inspect residual `||(I-Q)t-1||`, and avoid forming the inverse explicitly because inversion is more expensive and less stable than solving the system. For exact rational probabilities in a small model, rational elimination can verify an exact answer; for floating-point models, report precision and a residual.\n\nThe equations count discrete transitions. If transitions have state-dependent holding times, replace the right-hand constant vector 1 with the expected holding time per state. If the question asks for time until a particular absorbing subset rather than any absorbing state, treat other absorbing states as non-target outcomes or reformulate the state set; otherwise the computed stopping time answers a different question.\"<|final|>"}]}