Evaluating LLM Coding Ability with Two Challenging Algorithm Problems
This article presents a reproducible methodology for evaluating large language models' coding abilities using two hard algorithm problems: time-dependent shortest paths under periodic edge availability, and idempotent replay of out-of-order operation logs. It covers closed-form waiting-time computation, FIFO-based Dijkstra correctness, lexicographically minimal path reconstruction, and pitfalls such as deduplication scope and deterministic sorting—plus how to turn one-off evaluations into a CI pipeline with hidden test cases and repeated sampling.
1. Evaluation Approach: Cross-Generated Problems with Executable Scoring
Having one general-purpose LLM generate problems, another model solve them, and the problem generator grade the answers—while the solver admits its own mistakes—this “cross-generation” approach is informative not because of who wins, but because it replaces subjective impressions with executable, decidable test samples. A reproducible code evaluation must satisfy at least three conditions: each problem has a single, unambiguous semantics; grading depends on actual execution rather than text similarity; and boundary and complexity constraints are fixed explicitly in the problem statement.
The two problems below cover two typ属ical capabilities: graph modeling with mathematical simplification, and state machine semantics with idempotency and consistency.
2. Problem 1: Time-Dependent Shortest Path with Periodic Availability
Problem summary: a directed graph with n nodes and edges (u, v, phase, period, duration, cost). When arriving at u at time T, departure is only allowed if (depart + phase) % period == 0; otherwise the agent must wait until the next valid departure time. Arrival at v occurs at depart + duration, adding cost. The goal is to minimize arrival time first, then cost, and finally return the lexicographically smallest path by node IDs.
1. Closed-Form Solution for the Waiting Function
Don’t loop over candidate times—compute the smallest non-negative solution directly with modular arithmetic:
wait = (-(T + phase)) % period # 0 <= wait < perioddepart = T + waitarr = depart + duration
period can be as large as 1e9 and start_time as large as 1e18, so Python’s native integers handle this safely. Languages with fixed-width integers must explicitly use 64/128-bit types; any floating-point involvement will introduce precision errors at large magnitudes.
2. Why a Single Label per Node Suffices
The key property is FIFO (first-in, first-out): if T1 <= T2, then depart(T1) <= depart(T2), and therefore arr(T1) <= arr(T2). The waiting function never makes a later departure arrive earlier, so there is no need to keep multiple non-dominated labels—each node only needs “earliest arrival time + minimum cost at that time,” and Dijkstra’s greedy strategy holds.
import heapqdef timed_shortest_path(n, edges, s, t, start_time):adj = [[] for _ in range(n)]for u, v, phase, period, duration, cost in edges:adj[u].append((v, phase, period, duration, cost))best_t = [None] * nbest_c = [None] * nbest_t[s], best_c[s] = start_time, 0pq = [(start_time, 0, s)]while pq:T, c, u = heapq.heappop(pq)if best_t[u] != T or best_c[u] != c:continue # stale labelfor v, phase, period, duration, cost in adj[u]:arr = T + (-(T + phase)) % period + durationnc = c + costif (best_t[v] is None or arr < best_t[v]or (arr == best_t[v] and nc < best_c[v])):best_t[v], best_c[v] = arr, ncheapq.heappush(pq, (arr, nc, v))if best_t[t] is None:return Nonereturn best_t[t], best_c[t], rebuild_path(...)
Complexity is O(m log n) time and O(n + m) space—exactly matching the constraints of 2e5 nodes and 3e5 edges.
3. Lexicographically Minimal Paths Can’t Use “Full Paths in the Heap”
Pushing path tuples into the heap degrades each comparison to O(n) and blows up memory. The correct approach is two phases: first compute the optimal label (T*, C*), then greedily reconstruct forward. By FIFO and the additivity of cost, any prefix of an optimal path is itself the optimal label at that prefix’s endpoint (otherwise substituting a better prefix would improve both time and cost—a contradiction). So starting from s, at each step choose the smallest-numbered neighbor v among outgoing edges such that the resulting (arr, nc) exactly equals (best_t[v], best_c[v]), until reaching t.
4. Hidden Pitfall Checklist
period = 1: departure is allowed at any time,waitis always 0, and the problem degenerates to an ordinary shortest path;- Multiple equivalent paths with
cost = 0: the tie must be broken by lexicographic order, not insertion order; s == t: return(start_time, 0, [s])—don’t mistakenly report it as unreachable;- Multi-edges: parallel edges must all participate in relaxation; deduplicating them loses optimal solutions;
- Unreachable target: return
None, not(inf, inf, []).
3. Problem 2: Idempotent Replay of Out-of-Order Logs
Problem summary: logs of the form (ts, actor, op_id, kind, payload) are given out of order and must be replayed in ascending (ts, actor, op_id) order. Later logs with a duplicate op_id under the same actor are ignored. add / move / delete require existence and owner validation; snapshot records the visible state of a given set of IDs, with missing IDs recorded as None.
def reconcile(events):objs, seen, snaps = {}, set(), []ordered = sorted(enumerate(events), key=lambda p: (p[1][0], p[1][1], p[1][2], p[0]))for _, (ts, actor, op_id, kind, payload) in ordered:if (actor, op_id) in seen: # idempotency key is scoped to actor, not globalcontinueseen.add((actor, op_id))if kind == "add":oid, value = payloadobjs.setdefault(oid, {"owner": actor, "value": value})elif kind == "move":oid, new_owner = payloadif oid in objs and objs[oid]["owner"] == actor:objs[oid]["owner"] = new_ownerelif kind == "delete":if payload in objs and objs[payload]["owner"] == actor:del objs[payload]elif kind == "snapshot":label, ids = payloadsnaps.append((label, {i: (objs[i]["owner"], objs[i]["value"])if i in objs else None for i in ids}))return objs, snaps
The common mistakes are all about semantic boundaries: the idempotency key is the (actor, op_id) pair, not op_id alone; deduplication happens before validation (a duplicate log is swallowed even if invalid); when the full three-part sort key ties, the problem statement leaves it undefined—in engineering practice you should append the original index as a final tiebreaker and document it to guarantee determinism; snapshot is a read-only projection and must not mutate state. Overall complexity is O(n log n).
4. Turning Evaluation into a Pipeline
A single conversational prompt cannot support a reliable conclusion. Recommended practices: prepare at least 20 hidden test cases per problem, covering the pitfalls listed above; set runtime and memory limits, where exceeding either means failure; run multiple samples with the same prompt and report pass rates rather than a single result; grade only on return values, never on explanations; and automatically archive failed cases into a regression set. On the engineering side, this evaluation can be attached to a continuous integration pipeline—use container platforms for isolated execution environments, object storage for test cases and artifacts, and logging/monitoring services to track pass-rate trends. On Baidu AI Cloud, these generic capabilities can be combined directly into a closed loop without building the full infrastructure yourself.
5. Conclusion
The value of these two problems lies not in their difficulty, but in how they decompose “can the model write code” into attributable capability items: mathematical simplification and FIFO proofs, correctness of label relaxation, lexicographic reconstruction, idempotency semantics, and sorting determinism. The credibility of an evaluation comes from objective scoring, not a model’s self-assessment phrasing. Fix the hidden test cases, complexity constraints, and multi-sampling procedure in place, and any model’s progress—or regression, including your own in-house models—will immediately become visible.
