Evaluating LLM Code Generation: Hands-On Algorithm Challenges and Failure Analysis
This article explores how to scientifically evaluate the code generation capabilities of large language models through two custom-designed problems: a time-dependent shortest path problem (TC1) and an out-of-order log replay problem (TC2). It analyzes typical LLM failure modes—such as mishandling degenerate parameters, multi-level tie-breaking, and order-sensitive state semantics—and offers a practical methodology for building custom evaluation sets that expose real weaknesses beyond public benchmark scores.
How to Scientifically Evaluate LLM Code Generation: Lessons from Two Classic Algorithm Problems
Introduction
In recent years, large language models have advanced rapidly in code generation, and every major release arrives with impressive benchmark scores. However, leaderboard numbers often diverge from real engineering capability. One frequently overlooked fact is that public benchmark problems have very likely been seen by models during training, so scores cannot fully reflect a model’s genuine reasoning ability on unfamiliar problems.
Rather than targeting any specific model or product, this article uses a hands-on session with custom-designed problems to address a more universal question: how should evaluation problems be designed to truly expose the weaknesses of LLM code generation? Through two carefully constructed problems—time-dependent shortest path (TC1) and out-of-order log replay (TC2)—we analyze typical failure patterns of large models and provide actionable evaluation recommendations.
1. Why Custom Evaluation Problems Are Necessary
1.1 Limitations of Public Benchmarks
Common code evaluation benchmarks in the industry suffer from three inherent flaws:
- Data contamination risk: problems and their solutions are widely available on the public internet, so models may rely on memorization rather than reasoning;
- Narrow problem-type distribution: they overemphasize routine dynamic programming and string manipulation, while underrepresenting “state simulation with complex rules”;
- Single-dimensional evaluation criteria: they typically only compare final outputs, without examining edge-case handling, complexity control, or code robustness.
1.2 Design Principles for Good Problems
A problem that effectively differentiates model capability usually has the following characteristics:
- The rules can be manually and exhaustively verified, making it easy to construct a ground-truth answer;
- Multiple independent traps are hidden in the problem, so missing any one of them produces a wrong answer—allowing precise localization of a model’s weak points;
- The constraints force the correct algorithmic choice, so brute-force solutions cannot pass, testing the model’s complexity awareness;
- Multiple tie-breaking scenarios exist (equal time, equal cost, lexicographic order), testing the rigor of the model’s handling of multi-level comparison.
The two problems below were designed exactly according to these principles.
2. TC1: Time-Dependent Shortest Path—A Disaster Zone for LLMs
2.1 Problem Abstraction
Given a directed graph where each edge has the form (u, v, phase, period, duration, cost), traversal is only allowed when the departure time satisfies (depart + phase) % period == 0; otherwise, you must wait until the nearest valid departure time. The required output is a triple:
- The earliest arrival time;
- Among all earliest-arrival plans, the one with minimum total cost;
- If both are still tied, the lexicographically smallest node path.
The data scale reaches n ≤ 2×10^5 nodes, up to 3×10^5 edges, and time parameters up to 10^18.
2.2 Key Points of the Correct Solution
This is essentially a multi-objective shortest path problem on a time-dependent graph. The standard approach is a modified Dijkstra’s algorithm: the state is the node ID, and the priority key is the triple (arrival time, accumulated cost, path sequence). When arriving at node u at time T, the earliest departure along edge (u, v, phase, period, duration, cost) is:
wait = (phase - T) % period # Beware of modulo semantics for negative valuesdepart = T + waitarrive = depart + duration
The lexicographically smallest path cannot be compared directly in a scalar priority queue. Common techniques include encoding the path as a comparable sequence, or performing a secondary lexicographic comparison during relaxation.
2.3 Typical LLM Failures
In hands-on testing, AI coding tools exposed a large number of shared errors on this problem, each worth analyzing:
Trap 1: The degenerate case of period = 1. Here, every moment is a valid departure time, and the waiting logic should degenerate to zero wait. Some models produced logically broken modulo-wait formulas in this case, or incorrectly waited an extra cycle.
Trap 2: Multiple equivalent paths with cost = 0. When many paths share the same cost, all comparison pressure falls on lexicographic order. Models often compared only the two keys (time, cost) and dropped the lexicographic constraint entirely.
Trap 3: s == t. When the start equals the target, the correct answer is arrival time start_time, cost 0, and path [s]. Many models failed to handle this trivial case, returning None or entering unnecessary searches.
Trap 4: Multiple edges. There may be several edges with different parameters between the same pair of nodes, and the adjacency list must keep all of them. Some models overwrote entries when building the graph with a dictionary.
Trap 5: Large integers and floating point. With time parameters up to 10^18, mixing in floating-point arithmetic (e.g., using floats for modulo or division) causes precision loss and wrong answers. The correct approach is to use integer arithmetic throughout and to watch the sign semantics of modulo when (phase - T) is negative.
Trap 6: Uncontrolled complexity. Some models ignored the 2×10^5 scale and produced pseudo-polynomial solutions that enumerate all time slices per node—completely infeasible on real data.
Notably, these errors are not about “not knowing the algorithm,” but about insufficient ability to faithfully implement every rule in the problem statement. This is the core gap between LLMs and senior engineers: an engineer checks constraints one by one, while a model tends to generate a “plausible-looking” skeleton and wrap up hastily.
3. TC2: Out-of-Order Log Replay—A Test of State Consistency
3.1 Problem Abstraction
The input is a set of out-of-order logs, each of the form (ts, actor, op_id, kind, payload). The system maintains a set of objects, each with three fields: id / owner / value. The rules include:
- Logs are replayed in ascending order of
(ts, actor, op_id); - Subsequent logs with a duplicate
op_idunder the same actor must be ignored (idempotency); add: creates the object if it does not exist; ignored otherwise;moveanddelete: take effect only when the current owner equals the operation initiator;snapshot: records the visible state of the specified id list at that moment; non-existent ids are recorded asNone.
3.2 Key Points of the Correct Solution
This type of problem is a classic deterministic event-sourcing simulation. The core steps are:
- Stable sorting: sort by the composite key
(ts, actor, op_id); note that actor is a string, and the op_id comparison rule must match the problem statement; - Idempotent deduplication: maintain a seen set of
(actor, op_id)pairs and skip on hits; - Apply rules in order: for each operation, first validate permission (owner match), then mutate state;
- Snapshot semantics: a snapshot must read the live state “as replayed up to that moment,” not the post-hoc final state—this is the easiest place to go wrong.
3.3 LLM Performance and Failures
Compared to TC1, AI coding tools performed somewhat better on this problem, but typical issues remained:
- Wrong sort key: sorting only by
tsand ignoring the(actor, op_id)tie-breaker, leaving the application order of same-timestamp events undefined; - Misunderstood idempotency scope: treating
op_iddeduplication as globally unique rather than unique per actor; - Wrong permission-check timing: pre-filtering unauthorized operations before sorting, instead of checking against the owner at replay time—two completely different semantics, since ownership changes as move operations are applied;
- Wrong snapshot timing: applying all events first and backfilling snapshots afterward, yielding the final state instead of the historical state.
These errors reveal another LLM weakness: a lack of strict execution discipline for order-sensitive state-machine semantics. The rules are not complex, but each step depends on the correct execution of the previous one, and any ordering deviation cascades.
4. Distilling an Evaluation Methodology from Failures
4.1 Recommended Evaluation Workflow
Drawing on the hands-on experience above, we summarize a reusable workflow for evaluating LLM coding ability:
- Build your own problems: start from classic models (shortest path, event sourcing, concurrency control, etc.) and layer on three types of perturbation—multi-level comparison, degenerate parameters, and massive scale;
- Cross-validate: have one model design problems, another solve them, and an independent judge evaluate—but beware of “problem-setter bias,” since the problems themselves may be ambiguous or flawed. Ground-truth answers must be manually derived and confirmed;
- Trap instrumentation: design each hidden trap as an independent test case, producing fine-grained diagnostics instead of a single pass/fail verdict;
- Let the model self-review: ask the model to retrospec on its own wrong answers. An interesting phenomenon observed in testing: once the correct answer is shown, models can usually pinpoint their own mistakes accurately—suggesting their ability to “understand errors” outpaces their ability to “avoid errors.” That gap is itself an important evaluation signal.
4.2 Implications for Engineering Practice
For teams using AI coding assistants in production, these observations offer three takeaways:
- Never let a model write “edge-case-dense” code without review. Shortest-path, state-machine, and permission-checking code requires line-by-line constraint verification by a human;
- The value of test cases is further amplified. Since model failures concentrate on boundary conditions, high-quality unit tests (covering degenerate parameters, ties, and empty inputs) are the most effective safety net;
- Leverage the model’s ability to explain and self-review. Asking a model to explain how a piece of code behaves under every edge case is often more reliable than expecting it to write the code correctly in one shot. In human-AI collaboration, a three-stage workflow of “model generates + model self-reviews + human arbitrates” is far more trustworthy than single-shot generation.
5. Conclusion
The key to evaluating LLM coding ability is not whether a model can pass common problems, but whether you can construct probes that precisely pierce its weaknesses. Through the time-dependent shortest path and out-of-order log replay problems, this article demonstrated systematic LLM shortcomings in multi-level comparison, degenerate parameters, and order-sensitive semantics, and presented a methodology combining custom problem design, trap instrumentation, and model self-review.
As model capabilities continue to evolve, today’s “disaster zones” may be conquered in the next version. But two problems will persist for the long term: “leaderboard distortion under data contamination” and “rigorous handling of edge cases.” Maintaining an independent, continuously updated private evaluation set is infrastructure worth investing in for every team that takes AI-assisted coding seriously.
