Paper deep dive
StoryCoder: Narrative Reformulation for Structured Reasoning in LLM Code Generation
Geonhui Jang, Dongyoon Han, YoungJoon Yoo
Intelligence
Status: succeeded | Model: google/gemini-3.1-flash-lite-preview | Prompt: intel-v1 | Confidence: 96%
Last extracted: 4/18/2026, 1:37:36 AM
Summary
StoryCoder is a narrative-based prompting framework that improves LLM code generation by transforming fragmented problem descriptions into coherent natural language narratives. These narratives consist of a task overview, constraints, and example test cases, which help models form better mental models and algorithmic strategies. Experiments across 11 models and three benchmarks (HumanEval, LiveCodeBench, CodeForces) show an average 18.7% gain in zero-shot pass@10 accuracy.
Entities (5)
Relation Signals (4)
StoryCoder → transforms → Code Generation Questions
confidence 98% · STORYCODER, a narrative reformulation framework that transforms code generation questions into coherent natural language narratives
StoryCoder → improvesperformanceon → HumanEval
confidence 95% · Experiments across 11 models on HumanEval... demonstrate consistent improvements
StoryCoder → improvesperformanceon → LiveCodeBench
confidence 95% · Experiments across 11 models on... LiveCodeBench... demonstrate consistent improvements
StoryCoder → improvesperformanceon → CodeForces
confidence 95% · Experiments across 11 models on... CodeForces demonstrate consistent improvements
Cypher Suggestions (0)
No Cypher suggestions yet.
Abstract
Abstract:Effective code generation requires both model capability and a problem representation that carefully structures how models reason and plan. Existing approaches augment reasoning steps or inject specific structure into how models think, but leave scattered problem conditions unchanged. Inspired by the way humans organize fragmented information into coherent explanations, we propose StoryCoder, a narrative reformulation framework that transforms code generation questions into coherent natural language narratives, providing richer contextual structure than simple rephrasings. Each narrative consists of three components: a task overview, constraints, and example test cases, guided by the selected algorithm and genre. Experiments across 11 models on HumanEval, LiveCodeBench, and CodeForces demonstrate consistent improvements, with an average gain of 18.7% in zero-shot pass@10. Beyond accuracy, our analyses reveal that narrative reformulation guides models toward correct algorithmic strategies, reduces implementation errors, and induces a more modular code structure. The analyses further show that these benefits depend on narrative coherence and genre alignment, suggesting that structured problem representation is important for code generation regardless of model scale or architecture. Our code is available at this https URL.
Tags
Links
- Source: https://arxiv.org/abs/2604.14631v1
- Canonical: https://arxiv.org/abs/2604.14631v1
Trouble viewing inline? Open PDF directly →
Full Text
83,760 characters extracted from source content.
Expand or collapse full text
StoryCoder: Narrative Reformulation for Structured Reasoning in LLM Code Generation Geonhui Jang 1 , Dongyoon Han 2† , YoungJoon Yoo 1† 1 Dept. of Artificial Intelligence, Chung-Ang University 2 NAVER AI Lab csleivear1, yjyoo3312@cau.ac.kr dongyoon.han@navercorp.com Abstract Effective code generation requires both model capability and a problem representation that carefully structures how models reason and plan. Existing approaches augment reasoning steps or inject specific structure into how mod- els think, but leave scattered problem condi- tions unchanged. Inspired by the way humans organize fragmented information into coherent explanations, we proposeSTORYCODER, a nar- rative reformulation framework that transforms code generation questions into coherent natural language narratives, providing richer contex- tual structure than simple rephrasings. Each narrative consists of three components: a task overview, constraints, and example test cases, guided by the selected algorithm and genre. Experiments across 11 models on HumanEval, LiveCodeBench, and CodeForces demonstrate consistent improvements, with an average gain of18.7%in zero-shot pass@10. Beyond ac- curacy, our analyses reveal that narrative re- formulation guides models toward correct al- gorithmic strategies, reduces implementation errors, and induces a more modular code struc- ture. The analyses further show that these ben- efits depend on narrative coherence and genre alignment, suggesting that structured problem representation is important for code generation regardless of model scale or architecture. Our code is available here. 1 Introduction Problem-solving ultimately depends on how clearly the information is conveyed and understood. Effec- tive problem solving may require both the solver’s capability to interpret information and the way the problem is framed (Vessey, 1991; Kelton et al., 2010). However, in practice, task descriptions are incomplete or ambiguous, forcing solvers to in- fer missing details from context. These gaps are † Corresponding authors. especially challenging in complex tasks that de- mand contextual understanding or multi-step rea- soning. Large language models (LLMs) face the same difficulty: their performance depends not only on internal reasoning but also on how effectively the task is specified and interpreted (Laban et al., 2025). In this work, we investigate how to improve the delivery and interpretation of information in LLMs, focusing on code generation tasks. Pro- gramming tasks are particularly suitable for this study: they are built on logically distinct structures, and their solutions can be explicitly validated using test cases, making them ideal for examining how problem representation affects reasoning (Wang et al., 2025; Light et al., 2025). We introduceSTORYCODER, a narrative- based prompting method that transforms short, instruction-like problem statements into coherent natural language. This design is based on the find- ings of cognitive science that humans comprehend and reason more effectively when organizing frag- mented conditions into coherent mental models using analogical structures (Johnson-Laird, 1983; Gentner, 1983; Holyoak and Lu, 2021). In this framework, models identify the appropriate algo- rithm that will form the logic of the code, align it with a suitable narrative genre, and reformulate it into a story with three sections: task overview, constraints, and example input/output. (Figure 1) By connecting fragmented conditions into coherent descriptions, narratives help LLMs capture context and follow more structured reasoning. We evalu- ate STORYCODER on three benchmarks across 11 closed- and open-source models. Extensive exper- iments demonstrate consistent performance gains across diverse models and benchmarks. Beyond overall accuracy, we find that narrative prompts substantially increase the likelihood of selecting the correct algorithms and reduce im- plementation errors. In contrast, when narratives are expressed in mismatched genres, performance 1 arXiv:2604.14631v1 [cs.CL] 16 Apr 2026 drops significantly. This suggests that LLMs are sensitive to narrative structure and benefit from genre alignment in tasks such as code generation. These observations support our hypothesis that nar- ratives are a natural and effective tool to encourage integrative reasoning. Our key contributions are as follows: •We proposeSTORYCODER, a narrative-based prompting method for code generation that re- formulates fragmented prompts into coherent descriptions. •We demonstrate consistent empirical improve- ments across diverse models and benchmarks, achieving a18.7%average gain in zero-shot pass@10 accuracy. •We provide quantitative analyses showing that narrative reformulation guides LLMs toward correct algorithmic strategies, reduces imple- mentation errors, and induces more modular code structure. 2 Related Work Structured prompt engineering for code genera- tion. Recent work in code generation has increas- ingly focused on structuring prompts to improve the reasoning process of LLMs. Some approaches introduce explicit intermediate steps, such as con- trol structures or modular subcomponents, to guide program synthesis more reliably (Li et al., 2025a; Le et al., 2024; Huang et al., 2023). Recent work demonstrates that language-based input–output pat- terns can enable structured and verifiable reasoning in code generation (Li et al., 2025b). Related stud- ies further investigate how narrative or prose-style problem descriptions affect requirement extraction, using narrative framing as a condition to be evalu- ated in code generation (Haller et al., 2024). While many previous approaches present structured rea- soning through explicit intermediate steps or modu- lar decomposition, our methodSTORYCODERpro- vides a structured reasoning trajectory to the model through narrative-based prompt design. Prompt reformulation and test-time reasoning in LLMs. Another line of research examines how rephrasing prompts at test time affects the way LLMs reason on a task. Chain-of-thought prompting, especially when combined with self- consistency, helps models explore diverse reason- ing paths and improves robustness through out- put aggregation (Wei et al., 2022; Wang et al., 2023). Beyond explicit reasoning steps, rephras- ing task instructions influences how the model in- terprets the problem (Fu et al., 2024; Zhou et al., 2024). In the context of multiple-choice reason- ing tasks, narrative-based prompting has been ex- plored as a structured reasoning framework to sup- port the selection of answers among predefined choices (Sadiri Javadi et al., 2025). Building on these insights, our method reformulates prompts into coherent task-grounded narratives that inte- grate conditions, intent, and examples within a uni- fied structure for code generation. 3STORYCODER: Reformulating question into narratives 3.1 Conventional baselines for code generation Early evaluations of code generation relied on similarity-based metrics such as CodeBLEU, which were insufficient for assessing functional correctness. Recent benchmarks adopt execution- based evaluation using the pass@kmetric (Chen et al., 2021). Under this setting, we consider the fol- lowing baselines: Repeated Sampling, Paraphras- ing, and Chain-of-Thought (CoT) prompting. • Repeated sampling improves pass@kby gen- erating multiple outputs for the same input via stochastic decoding, typically with high tempera- ture (Chen et al., 2021). Increasing the number of candidates raises the likelihood that at least one solution is correct. •Chain-of-thought (CoT) prompts the model to generate intermediate reasoning steps prior to producing code (Wei et al., 2022; Huang et al., 2023). By making the reasoning process explicit, CoT encourages stepwise planning. • Structured chain-of-thought (SCoT) extends CoT for code generation by incorporating pro- gram structures (sequence, branch, and loop) into the intermediate reasoning steps (Li et al., 2025a). It guides the model to think from the perspective of the source code before generating the output. 3.2 Narrative reformulation for deeper comprehension The approaches discussed in Section 3.1 are useful, but they have a limitation: they either expand out- puts without changing the input, or introduce rea- soning steps that do not always reflect how models actually process the problem (Turpin et al., 2023). 2 Narrative Generator (푓 narr ) 1. Identify Algorithm Category Decide which algorithm category the problem most closely belongs to: - Dynamic Programming ... - Simulation and Implementation 2. Select Narrative Genre Choose a narrative genre that naturally aligns with the problem and the chosenalgorithm. 3. Reformulate into Narrative Transform the coding problem into a story- style description. The reformulated narrative must include the following three components: -Task Overview: ... -Constraints: ... -Example Input/Output: ... Narrative Transformation Guidelines Solver (푓 solve ) def minCostDP(n, l): for i in range(n): ... (i) Algorithm & Genre Selection (i) Solution Generation Question 푄 푖 Question 푄 푖 Problem Statement (i) Narrative Reformulation Evaluating Solutions with Test Cases Input: 3, [2, 1, 5] Output: 34 ... ✓ Narrative 푖 Algorithm: Dynamic Programming Genre: Fantasy Adventure (Optional) Figure 1: Overview ofSTORYCODERframework. Given a questionQ i , (i) model first identifies an algorithmic category and selects a narrative genre, then (i) reformulates the problem into a structured narrativeN i consisting of task overview, constraints, and example input/output, and (i) passes the narrative (optionally concatenated with Q i ) to a solver model to generate code solutions, which are then verified with test cases. Research in cognitive science suggests that more effective reasoning emerges when fragmented con- ditions are organized into a unified relational struc- ture (Gentner, 1983). Inspired by this, we propose a narrative reformulation framework that reorga- nizes task representation, encouraging the model to form a more coherent and semantically grounded understanding of the input. We construct a framework that reformulates code generation questions into a narrative format in three stages as shown in Figure 1: (i) for thei-th ques- tionQ i , choosing an appropriate algorithmic cate- gorya i and a narrative genreg i ; (i) rewritingQ i as a structured narrativeN i with three parts: task overview, constraints, and example input/output; and (i) solving the task usingN i . Here, the al- gorithma i denotes the algorithmic category that the model judges to be the most appropriate for the given problem, chosen from the eight predefined categories in Figure A. The genreg i denotes the narrative style, selected freely by the model to align with the problem and the chosen algorithma i . We generateNnarrative variants for each questionQ i and denote the index of each reformulation variant byj ∈ 1, . . . , N. Note that generating these narrative variants differs from simply drawing mul- tiple solutions, as each narrative provides a distinct perspective and plot that broadens the model’s rep- resentational space for interpreting and reasoning about the task. Formally, the overall pipeline can be described as follows: a j i , g j i , N j i N j=1 = f narr (Q i ) Ans(N j i ) = f solve (N j i ), (1) wheref narr is the generator model that formulates narratives andf solve is the solver model that gen- erates code solutionsAns(·). We refer to the case wheref narr andf solve are the same model as the self- solving setting, and the case where they differ as the cross-model setting. Note thatN j i ∼ P(·| a j i , g j i ), whereN j i denotes thej-th narrative variant of the questionQ i , andPdenotes the conditional distri- bution of narratives given the algorithmic category a j i and genre g j i selected by f narr . In stage (i), unlike the prior work (Sadiri Javadi et al., 2025), we carefully design the narrative com- ponents for programming tasks, where precise for- mat and formal constraints are required. To ensure that the reformulated prompt preserves both nar- rative coherence and computational strictness, we divide a narrativeN j i into three parts: •Task Overview(TO j i ): presents the coding ob- jective within a narrative frame, integrating scat- tered conditions into a coherent system that guides comprehension and reasoning. • Constraints(C j i ): reframes input ranges, time limits, and rules as natural restrictions in the story, allowing the model to internalize constraints within the narrative space. •Example Input/Output(E j i ): integrates sam- ple test cases into contextual scenarios, aligning input/output examples with the story structure, so that formal coding task requirements are pre- served within the narrative space. This three-part structure is motivated by a prin- ciple observed in both cognitive science and re- 3 You are given an integer array nums and a positive integer 푘. Return the sum of the maximum and minimum elements of all subsequences of nums with at most 푘elements. ... Constraints: 1≤nums.length ≤10 5 Example: Input: nums = [1,2,3], 푘= 2 Output: 24 -Task Overview The brave adventurer, Elara, must embark on a perilous quest to reforge the legendary Sunstone, a relic fractured into countless shards. ... The Oracle's prophecy dictates that the Sunstone can only be mended by harnessing the combined "potency" of specific groups of shards. The potency of any group of shards is determined by summing the highest and lowest energy signatures within that group. Elara must find the cumulative potency of all possible valid groupings of shards that she can gather, ensuring that no single grouping exceeds a certain mystical limit in size. -Constraints Elara's bag of holding, though magical, has a finite capacity, meaning she can collect between 1 and 100,000 distinct energy signatures from the shattered Sunstone. -Example Input/Output Input: The Oracle provides Elara with a small training set of shard energies: [1, 2, 3], and a mystical group size limit: 푘=2. Output: The total cumulative potency Elara reports is 24. ✓ ✗ def minMaxSums(nums: List[int], k: int): for i in range(n): for j in range(i, n): min_val = nums[i] max_val = nums[j] ... Calculate combinations for choosing remaining elements from n -length elements. ... def minMaxSums(nums: List[int], k: int): def nCr_mod_p(n_val, r_val): if r_val < 0 or r_val > n_val: return 0 ... Calculate the number of times each element contributes as a minimum or maximum using combinatorics and sums them up. ... Original Question Narrative Reformulation (a) Narrative Transformation (b) Model Response Correct (using Combinatorial Counting) Time Limit Exceeded (due to Double Loop) Figure 2: Example of narrative reformulation. The narrative representation bridges problem description and model reasoning, guiding the model from inefficient non-optimal solutions toward algorithmic strategies. cent analyses of LLM behavior: effective reason- ing depends on forming a coherent and specified problem representation before solution generation. Cognitive science research on mental models sug- gests that humans reason by constructing structured representations that capture the essential relations of a situation within a unified mental representa- tion (Johnson-Laird, 1983). Similarly, recent stud- ies on LLM prompting have shown that underspec- ified or fragmented problem descriptions can lead to degradation in model performance (Yang et al., 2025).STORYCODERbuilds on this observation by organizing task overview, constraints, and ex- amples into a single narrative, with the goal of en- couraging the model to form a consistent high-level problem representation prior to code generation. Together, these three components of the narrative N j i = TO j i , C j i , E j i standardize the reformula- tion process, ensuring that all essential details of the original question of code generation are pre- served while also allowing cognitive principles to be naturally integrated into the narrative structure. Transformation examples are provided in Figure 2 and Appendix B.3. 4 Experiments 4.1 Experimental settings Models. We evaluate a total of 11 models of vary- ing sizes. Among open-source models, we use the instruction-tuned versions of Deepseek-Coder 6.7B (Guo et al., 2024), Deepseek-Coder-V2- Lite (Zhu et al., 2024), Llama-3.1 8B (Grattafiori et al., 2024), Gemma-2 9B and 27B (Team et al., 2024), Qwen-2.5-Coder 7B and 32B (Hui et al., 2024), and Mistral-Small 24B (Mistral AI, 2025). For readability, we omit ‘Instruct’ from all the model names below. For closed-source models, we include Claude-3.5-Haiku (Anthropic, 2024), Gemini-2.5-Flash (Comanici et al., 2025), and GPT- 4.1-mini (OpenAI, 2025). The narrative and code are generated with a temperature of 1.0 and 0.2. Dataset. We evaluate on three benchmarks: Hu- manEval (Chen et al., 2021), a dataset with function signatures and docstrings; LiveCodeBench (Jain et al., 2024), a large-scale dataset covering various programming problems; and CodeForces (Mirza- yanov, 2010), real-world algorithmic problems from competitive programming. For HumanEval, we exclude questions that are invalid or contain in- correct sample input/output, resulting in a filtered set of 105 questions. For LiveCodeBench, we use the 175 questions from release-v6, sourced from AtCoder (Ueda and Inc., 2012) or LeetCode (Tang, 2015). For CodeForces, we apply filtering based on question length and difficulty, yielding a final set of 265 questions. For detailed filtering criteria and additional results, see the Appendix B.2. Metric and evaluation. We report the results using the pass@kmetric. The pass@kmetric measures 4 Table 1: Pass@10 performance on three benchmarks. The upper part of the table reports closed-source models, while the lower part reports open-source models. We evaluateSTORYCODERagainst representative prompting baselines across 11 models to assess its generality. Our method consistently outperforms repeated sampling (RS), CoT, and SCoT across the benchmarks and models, especially with larger gains on challenging benchmarks. HumanEvalLiveCodeBenchCodeForces ModelRSCoTSCoTNarr.RSCoTSCoTNarr.RSCoTSCoTNarr. Gemini-2.5-Flash96.19 95.1995.1096.1953.14 50.6350.8657.1460.00 53.1952.1367.55 GPT-4.1-mini96.19 94.2995.2494.2950.29 52.5749.7156.5738.87 43.0246.4150.57 Claude-3.5-Haiku85.71 83.8178.1094.2933.71 29.1426.2938.2947.17 19.6224.1550.95 Average92.7091.1089.4894.9245.7144.1142.2950.6748.6838.6140.9056.36 DSCoder 6.7B82.86 83.8184.3190.4822.29 22.8623.4327.4314.34 11.6911.8419.62 DSCoder-V2-Lite78.10 80.9585.2993.3328.57 29.1426.2934.2926.04 26.2823.8833.96 Llama-3.1 8B 79.05 76.1975.4981.9021.14 24.5722.8627.439.4410.928.8320.38 Gemma-2 9B63.81 62.8660.7882.8620.00 19.4320.5726.2912.83 10.7412.6222.26 Gemma-2 27B76.19 80.9577.4587.6227.43 25.7125.7134.2923.77 22.3820.6432.07 Qwen-2.5-Coder 7B89.52 92.3892.1693.3326.86 29.7126.8633.1419.62 20.5818.5527.92 Qwen-2.5-Coder 32B92.38 90.4895.1094.2930.86 34.2936.0040.0015.47 24.9824.7228.68 Mistral-Small 24B 88.57 90.4890.2094.2933.71 34.8633.7134.8630.18 27.0133.0043.77 Average81.3182.2682.6089.7626.3627.5726.9332.2218.9619.3219.2628.58 Table 2:Proportion of valid narratives where the modelf narr follows the transformation guidelines properly. For the DeepSeek (DS) and Qwen fam- ilies, we use their base instruction-tuned versions (DeepSeek-V2-Lite-Chat (Zhu et al., 2024), Qwen2.5- 7B/32B-Instruct (Yang et al., 2024)) rather than coding- specialized variants, as narrative transformation is closer to a basic instruction-following task. DSGemmaLlama MistralQwen ModelV29B 27B8B24B7B 32B Valid (%) 68.1 51.7 96.036.786.937.8 76.6 the probability that at least one correct solution is found amongksampled outputs. Following Hu- manEval, we consider a generated solution to be correct only when it passes all test cases (see Ap- pendix B.1.) In our experiments, we setN = 5narrative vari- ants per question. For the narrative setting in the main paper, we aggregate 10 total responses per question: five narrative-only variantsN j i 5 j=1 and five narrative concatenated with the original ques- tionN j i , Q i 5 j=1 . Both forms follow the same reformulation pipeline, with the original question appended as additional input in the concatenated variant. To ensure fairness, the repeated sampling baseline generates 10 samples per question, match- ing the total number of samples used in the narra- tive setting. The pass@5 results for each individual set of five variants are reported in Appendix A.1. 4.2 Experimental results Table 1 presents pass@10 results on three coding benchmarks. For closed-source models, we adopt a self-solving setting wheref narr = f solve , while for open-source models, we adopt a cross-model setting, i.e., the narratives are generated by Gemini- 2.5-Flash (f narr ) and solved by each open-source model (f solve ). Repeated sampling relies solely on stochastic decoding rather than exploring represen- tation diversity, CoT often produces unstructured explanations that are inappropriate for program- ming tasks, and SCoT introduces program-level structure but does not alter how the problem itself is represented. Meanwhile, narrative prompting consistently outperforms all baselines across all benchmarks and models, demonstrating its general effectiveness for code generation. Improvements are more pronounced on challenging benchmarks such as CodeForces and LiveCodeBench. Addition- ally, the pass@kcurves in Appendix A.4 show that narrative prompting outperforms the baseline ask increases. Additional experimental results, includ- ing evaluations on the latest models, are provided in Appendix A. We initially considered evaluating open-source models in a strict self-solving setting (i.e.,f narr = f solve ). However, as shown in Table 2, open-source models often fail to reliably follow the required nar- rative format, resulting in substantial differences in valid narrative ratios. To enable a more equi- table comparison, we select the top-3 open-source models with the highest valid narrative rates (Qwen 2.5 32B Instruct, Mistral-Small 24B Instruct, and 5 Table 3: Pass@kperformance of open-source models for self-solving scenarios. N-Q, N-M, and N-G correspond tof narr using Qwen2.5 32B Instruct, Mistral-Small 24B Instruct, and Gemma 2 27B Instruct, respectively. Repeated sampling (RS) is evaluated with pass@10. Narrative-based scores are computed as pass@kwithk = n∈ [8, 10], using the maximum number of valid narratives per question, and the Used Samples Ratio denotes the proportion of samples used for scoring. Narratives generated by open-source models still improve performance. HumanEvalLiveCodeBenchCodeForces RSN-QN-MN-GRSN-QN-MN-GRSN-QN-MN-G Used Samples Ratio100.0 64.42 97.14 95.24100.0 68.00 79.77 100.0100.0 65.4986.598.9 DSCoder 6.7B82.86 92.54 86.2787.022.29 19.33 23.19 22.8613.12 12.34 13.14 12.92 DSCoder V2 Lite78.10 91.04 92.1690.028.57 28.57 31.88 29.7125.16 30.00 32.25 28.17 Llama 3.1 8B79.05 85.07 81.3784.021.14 22.69 25.3624.08.1114.34 14.56 14.20 Gemma 2 9B63.81 86.57 85.2985.020.00 19.33 22.46 22.8611.69 17.23 17.36 18.36 Gemma 2 27B 76.19 88.06 88.2484.027.43 25.21 26.09 28.5722.38 27.86 30.18 27.06 Qwen 2.5 Coder 7B89.52 94.03 94.1290.026.86 28.57 33.33 29.7119.30 21.02 21.82 21.78 Qwen 2.5 Coder 32B92.38 95.52 94.1293.030.86 32.77 36.96 40.5715.08 23.40 24.02 26.06 Mistral-Small 24B88.57 92.54 92.1689.033.71 31.93 35.51 32.5729.23 32.23 34.68 33.52 Average81.3190.6789.2287.7526.3626.0529.3528.8618.0122.3023.5022.76 Table 4: Pass@10 performance with and without Ex- ample I/O. The gap between RS andSTORYCODER widens when Example I/O is removed, demonstrating that narrative semantics alone are sufficient to enhance reasoning. HumanEvalLiveCodeBenchCodeForces Setting RSNarr.RSNarr.RSNarr. w/ I/O96.19 96.1953.1457.1460.00 67.55 w/o I/O93.33 96.1938.2952.0035.10 57.36 Gemma 2 27B Instruct) and use them as narrative generators (f narr ). Although this setup is not strict self-solving, this relaxed configuration allows us to assess whether narrative reformulation improves performance when narratives are produced by open- source models rather than relying on a strong gen- erator. For detailed filtering criteria and examples of invalid narratives, refer to Appendix B.4. In Table 3, even in the self-solving setting of open-source models,STORYCODERconsistently improves performance across all benchmarks. On HumanEval, narratives generated by Qwen 2.5 32B (N-Q) show the strongest improvements across solvers. In contrast, on both LiveCodeBench and CodeForces, Mistral-Small 24B narratives (N-M) achieve the highest performance. These results sug- gest that narrative effectiveness for open-source models depends on how well the generator con- structs and interprets the reformulation, with the optimal choice varying by the pretrained knowl- edge of the generator and the complexity of the target benchmark. 4.3 Ablation study To isolate the contribution of narrative seman- tics from that of example I/O, we conduct an ab- lation study comparing repeated sampling (RS) andSTORYCODERwith and without example I/O across all three benchmarks using Gemini-2.5- Flash. The results in Table 4 reveal two key find- ings. First, both methods degrade without exam- ples, confirming that it is a fundamental compo- nent across prompting strategies. Second, the performance drop ofSTORYCODERis substan- tially smaller than that of RS (avg. 5.11%p vs. 14.20%p), demonstrating that narrative semantics alone, through reformulated task overview and con- straints, are sufficient to enhance reasoning even in the absence of examples. We further note that this binding is deliberately designed: example I/O is inherent to code generation benchmarks, and its coherent integration into the narrative is itself a meaningful contributor to the gains. For additional ablations, see Appendix A.2. 5 Discussion In this section, we analyze how and why narrative reformulation improves code generation from mul- tiple perspectives: whether narratives expand the solution space with algorithmic agreement (Sec- tion 5.1), error decomposition at the algorithm and implementation levels (Section 5.2), the role of narrative coherence among components (Sec- tion 5.3), whether LLMs recognize an optimal nar- rative space (Section 5.4), and code-level prop- erties of generated solutions (Section 5.5). For Sections 5.1 and 5.2, given a code solution gener- ated by the solver modelf solve , we query another 6 Figure 3: Effect of narrative reformulation. The x- axis denotes coverage (pass@10), and the y-axis shows the agreement ratio, the proportion of correct solutions consistent with the initial chosen algorithm,a i . Nar- rative reformulation simultaneously achieves broader coverage and higher algorithmic fidelity. model instancef alg to identify the algorithm un- derlying each generated solution. This procedure is similar to back-translation in machine transla- tion (Sennrich et al., 2016; Wang et al., 2025). All experiments are conducted with Gemini-2.5-Flash. 5.1 Coverage and algorithmic agreement We usef alg to extract back-translated algorithms from the outputs off solve and compare them with a j i , the algorithms initially predicted byf narr and incorporated into the narratives. Formally, we de- fine the agreement ratio as the fraction of correct solutions whose back-translated algorithms match a j i . We also define coverage as the proportion of problems for which at least one correct solution is generated, which is equivalent to pass@kwhenk equals the number of generated solutions. In Figure 3, coverage increases on challenging benchmarks such as LiveCodeBench and Code- Forces, indicating that narratives expand the solu- tion space, especially for harder tasks. The agree- ment ratio increases across all benchmarks, demon- strating that the initially selected algorithm is faith- fully reflected in the generated solutions. Together, these results show that narratives enable broader coverage and strengthen algorithmic agreement. 5.2 Decomposing narrative contributions Solutions to code generation tasks can be decom- posed into algorithms or sketch ideas, where se- lecting the right algorithm is necessary to arrive at a correct solution (Wang et al., 2025). To ana- lyze how models follow this process, we categorize their outputs into three outcomes as shown in Fig- Code correct? (i) Correct Solution Algorithmic approach appropriate? (i) Implementation (2) Error (i) Wrong Algorithm Yes No No Yes Figure 4: Decomposition of model outputs into (i) correct solution, (i) implementation errors, and (i) incorrect algorithm choice. (Top) Flowchart for catego- rizing model outputs. (Bottom) Ratio of each category under repeated sampling vs.STORYCODER. Narrative reformulation steers models toward correct algorithmic strategies and implementations. ure 4: (i) correct solutions, (i) incorrect responses where the chosen algorithm is appropriate but the implementation leads to an error, and (i) incorrect responses by selecting the wrong algorithm. For steps (i) and (i) of the categorization, we automatically extract a golden algorithm usingf alg . Specifically, we take all generated code solutions confirmed to be correct, from either the original or narrative problems, and queryf alg to back-translate the algorithm. We then determine the golden algo- rithma ∗ i by majority voting among the candidates: a ∗ i = MajorityVote n f alg (Ans(X i )) X i ∈ Q i ∪N j i N j=1 , Ans(X i ) is correct o . Thea ∗ i is used to evaluate whether incorrect solu- tions nevertheless adopt the correct algorithm, with such cases classified as (i) implementation errors (e.g., incorrect loop bounds). To better isolate the effect of representation change, we exclude triv- ial cases where generations for both original and narrative are either all correct or all incorrect. As shown in Figure 4, across both benchmarks, narratives increase the proportion of correct solu- tions while reducing both implementation errors and incorrect algorithm choices. This suggests that narrative reformulation improves procedural reasoning at both the algorithm selection and im- plementation levels. 7 Figure 5: Comparison of pass@kcurves across differ- ent prompt settings. Permuted narratives (components mixed across variants) outperform original prompts but remain below complete narratives, indicating the impor- tance of coherence (Section 5.3). Misaligned narratives (genres forced from incongruent sets) degrade perfor- mance, showing that proper representation contributes to effective problem solving (Section 5.4). 5.3 Component coherence matters Coherent integration of information components facilitates comprehension more effectively than disparate sources (Chandler and Sweller, 1991). Building on this, we design experiments that per- mute narrative components across variants to ex- amine whether coherent integration contributes to the performance gains, allowing us to distinguish between the informational benefits of narratives and the additional gains from the integration. Recall that each narrative reformulationN j i , thej-th variant ofQ i , consists of three parts: N j i = TO j i , C j i , E j i . In the permuted setting, we construct a new narrative e N j 1 ,j 2 ,j 3 i by sampling these components from different variants: e N j 1 ,j 2 ,j 3 i =TO j 1 i , C j 2 i , E j 3 i , where j 1 ̸= j 2 , j 1 ̸= j 3 , and j 2 ̸= j 3 . We compare three conditions: Original (Q i ), with- out narrative reformulation; Complete Narrative (N j i ), all components from the same variantj; and Permuted Narrative ( e N j 1 ,j 2 ,j 3 i ), each com- ponent drawn from a distinct variant. Surprisingly, permuted narratives still outperform the original prompts across allkas shown in Figure 5. Narra- tive reformulation provides informational benefits even when components are drawn from different variants. However, the permuted narratives fall short of the complete narratives, suggesting that narrative components are most effective when they form a coherent whole, with the full gains obtained through a unified structure. 5.4 Genre alignment drives performance Information is understood differently depending on its style or framing (Gentner, 1983; Thibodeau and ModelNarrative GenreRatio (%) Gemini “Fantasy Adventure”12.5 “Sci-Fi / Exploration”7.0 “Fantasy / Quest”6.9 ChatGPT “Fantasy Adventure”23.7 “Fantasy Quest”17.1 “Epic Fantasy Quest”14.8 Claude “Mathematical Mystery”6.3 “Mathematical Mystery Adventure” 5.5 “Strategic Puzzle Adventure” 4.0 (a) Top three narrative genres selected by each model. Fantasy Adventure Sci-Fi / Exploration Mathematical Mystery Obituary Column (b) PCA visualization of genre embeddings. Figure 6: Narrative genre preferences across mod- els. (a) The detailed genres with their ratio for each model; (b) PCA visualization of text embeddings of genre names selected by each model. Boroditsky, 2011). We identify narrative genre as a primary factor that shapes the style and structure of problem descriptions. Figure 6 shows the distribu- tion of genres selected by the three closed-source models in Section 4 across all benchmarks. Gemini- 2.5-Flash and ChatGPT-4.1-mini choose genres such as “Fantasy Adventure,” whereas Claude-3.5- Haiku favors “Mathematical Mystery.” This sug- gests that each model develops its own preferred genre cluster within the narrative space. To examine whether this genre preference re- flects a functionally meaningful structure, we de- liberately replace these well-aligned genres with incongruent ones. To this end, we manually curated G mis , a set of 20 misaligned genres with adminis- trative, legal, or memorial characteristics, disjoint from the genres naturally favored by the models. Whilef narr selects genres freely based onQ i in the standard setting, we instead enforce the genre g mis to be drawn fromG mis , obtaining Misaligned NarrativesN j,mis i ∼ P(· | a j i , g mis ) . Details are 8 Table 5: AST-based structural properties of correct solutions generated by repeated sampling (RS) and nar- rative prompting (Narr.). ( ∗ p < 0.01, ∗ p < 0.001) LiveCodeBenchCodeForces Metric RSNarr.RSNarr. Avg. functions0.9010.978 ∗ 1.8202.338 ∗ Helper func. rate39.7%39.8%41.4%48.6% ∗ AST depth9.0619.293 ∗ 11.033 11.272 ∗ provided in Appendix B.5. As shown in Figure 5, misaligned narratives show reduced performance compared to complete narratives across both benchmarks. This indicates that not all narratives are equally effective and that LLMs perform best when prompts align with gen- res conducive to reasoning. These findings suggest that LLMs recognize an optimal narrative space, and that representation alignment between problem description and model reasoning is a key factor in effective code generation. 5.5 Code-level structural analysis While pass@kand error decomposition measure functional correctness and algorithmic alignment, they do not directly measure whether narrative prompting induces more structured code at the im- plementation level. To address this, we extract the abstract syntax tree (AST) of each correct solution and compute three structural metrics. We exclude HumanEval from this analysis, as its format requires completing code within a single predefined function, which artificially constrains structural variation. For LiveCodeBench and Code- Forces, we compute: (i) Average functions, the mean number of function definitions per solution; (i) Helper function rate, the proportion of solutions containing at least two functions or a nested func- tion definition; and (i) AST depth, the maximum depth of the tree. The statistical significance is assessed using a one-sided Mann–Whitney U test. As shown in Table 5, our method induces more frequent decomposition into sub-functions, higher helper function usage, and deeper structural hi- erarchies across both benchmarks. These results complement the algorithm agreement analysis in Section 5.2: while that analysis shows narrative prompting guides models toward the correct al- gorithmic strategy, the AST-level results further demonstrate that it also encourages more modular and stepwise implementation, suggesting that nar- rative reformulation improves code generation at both the algorithmic and structural levels. 6 Conclusion In this work, we proposed STORYCODER, a frame- work that reformulates coding problems into co- herent narratives to promote integrative reasoning in LLMs, showing consistent performance gains across diverse benchmarks. Beyond demonstrat- ing improved coverage and algorithmic alignment, our findings suggest that narrative coherence and representation alignment are key factors that shape problem-solving effectiveness. More broadly, our study shows the role of narratives as guiding frame- works that help organize and contextualize com- plex tasks. We expect that future work will ex- plore adaptive genre selection, automated narrative refinement, and the extension of narrative-based prompting to domains such as mathematics, multi- modal reasoning, and scientific discovery. 7 Limitations Method limitations. The effectiveness of STO- RYCODER depends in part on the expressive and instruction-following capacity of the narrative gen- erator, particularly for open-source models. Per- formance gains are also smaller on simpler bench- marks such as HumanEval, where high-level narra- tive abstraction provides less benefit. Overall, the method is most effective when such reformulation is both feasible and meaningful. Scope of applicability. The proposed method is designed for competitive programming tasks with well-defined inputs, outputs, and constraints, and has not yet been validated on open-ended software engineering tasks or larger repository-level settings. Furthermore, defining what constitutes an optimal narrative transformation remains an open question. Future work could explore principled criteria for evaluating narrative quality beyond functional cor- rectness. Data and evaluation. This study evaluates perfor- mance primarily through execution-based bench- marks using the pass@kmetric. While we com- plement this with an AST-based analysis to assess structural patterns, evaluation using human judg- ment or software quality metrics remains for future work. 9 Acknowledgment This work was supported by the Institute of In- formation&Communications Technology Plan- ning&Evaluation (IITP) grant funded by the Ko- rea government (MSIT) [RS-2021-I211341, Artifi- cial Intelligence Graduate School Program (Chung- Ang University) and RS-2022-I220124, Develop- ment of Artificial Intelligence Technology for Self- Improving Competency-Aware Learning Capabili- ties]. SNUAILAB, corp, supports this work. References Anthropic.2024.Claude3.5haiku. https://w.anthropic.com/news/ 3-5-models-and-computer-use. Paul Chandler and John Sweller. 1991. Cognitive load theory and the format of instruction. Cognition and instruction, 8(4):293–332. Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde De Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, and 1 others. 2021. Evaluating large language models trained on code. arXiv preprint arXiv:2107.03374. Gheorghe Comanici, Eric Bieber, Mike Schaekermann, Ice Pasupat, Noveen Sachdeva, Inderjit Dhillon, Mar- cel Blistein, Ori Ram, Dan Zhang, Evan Rosen, and 1 others. 2025. Gemini 2.5: Pushing the frontier with advanced reasoning, multimodality, long context, and next generation agentic capabilities. arXiv preprint arXiv:2507.06261. Junbo Fu, Guoshuai Zhao, Yimin Deng, Yunqi Mi, and Xueming Qian. 2024. Learning to paraphrase for alignment with llm preference. In EMNLP (Find- ings), pages 2394–2407. Dedre Gentner. 1983. Structure-mapping: A theoretical framework for analogy. Cognitive science, 7(2):155– 170. Aaron Grattafiori, Abhimanyu Dubey, Abhinav Jauhri, Abhinav Pandey, Abhishek Kadian, Ahmad Al- Dahle, Aiesha Letman, Akhil Mathur, Alan Schelten, Alex Vaughan, and 1 others. 2024. The llama 3 herd of models. arXiv preprint arXiv:2407.21783. Daya Guo, Qihao Zhu, Dejian Yang, Zhenda Xie, Kai Dong, Wentao Zhang, Guanting Chen, Xiao Bi, Yu Wu, YK Li, and 1 others. 2024. Deepseek- coder: When the large language model meets programming–the rise of code intelligence. arXiv preprint arXiv:2401.14196. Patrick Haller, Jonas Golde, and Alan Akbik. 2024. PECC: Problem extraction and coding challenges. In Proceedings of the 2024 Joint International Con- ference on Computational Linguistics, Language Resources and Evaluation (LREC-COLING 2024), pages 12690–12699, Torino, Italia. ELRA and ICCL. Keith J Holyoak and Hongjing Lu. 2021. Emergence of relational reasoning. Current Opinion in Behavioral Sciences, 37:118–124. Dong Huang, Qingwen Bu, Yuhao Qing, and Heming Cui. 2023. Codecot: Tackling code syntax errors in cot reasoning for code generation. arXiv preprint arXiv:2308.08784. Binyuan Hui, Jian Yang, Zeyu Cui, Jiaxi Yang, Dayiheng Liu, Lei Zhang, Tianyu Liu, Jiajun Zhang, Bowen Yu, Keming Lu, and 1 others. 2024. Qwen2. 5-coder technical report. arXiv preprint arXiv:2409.12186. Naman Jain, King Han, Alex Gu, Wen-Ding Li, Fanjia Yan, Tianjun Zhang, Sida Wang, Armando Solar- Lezama, Koushik Sen, and Ion Stoica. 2024. Live- codebench: Holistic and contamination free eval- uation of large language models for code. arXiv preprint arXiv:2403.07974. Philip Nicholas Johnson-Laird. 1983. Mental models: Towards a cognitive science of language, inference, and consciousness. Harvard University Press. Andrea Seaton Kelton, Robin R Pennington, and Brad M Tuttle. 2010. The effects of information presentation format on judgment and decision mak- ing: A review of the information systems research. Journal of Information Systems, 24(2):79–105. Philippe Laban, Hiroaki Hayashi, Yingbo Zhou, and Jennifer Neville. 2025. Llms get lost in multi-turn conversation. arXiv preprint arXiv:2505.06120. Hung Le, Hailin Chen, Amrita Saha, Akash Gokul, Doyen Sahoo, and Shafiq Joty. 2024. Codechain: Towards modular code generation through chain of self-revisions with representative sub-modules. In The Twelfth International Conference on Learning Representations. Jia Li, Ge Li, Yongmin Li, and Zhi Jin. 2025a. Struc- tured chain-of-thought prompting for code genera- tion. ACM Transactions on Software Engineering and Methodology, 34(2):1–23. Junlong Li, Daya Guo, Dejian Yang, Runxin Xu, Yu Wu, and Junxian He. 2025b. CodeIO: Condensing rea- soning patterns via code input-output prediction. In Forty-second International Conference on Machine Learning. Jonathan Light, Yue Wu, Yiyou Sun, Wenchao Yu, Yanchi Liu, Xujiang Zhao, Ziniu Hu, Haifeng Chen, and Wei Cheng. 2025. SFS: Smarter code space search improves LLM inference scaling. In The Thir- teenth International Conference on Learning Repre- sentations. Mikhail Mirzayanov. 2010. Codeforces.https:// codeforces.com/. Online competitive program- ming platform. 10 Mistral AI. 2025.Mistral-small-24b-instruct- 2501.https://huggingface.co/mistralai/ Mistral-Small-24B-Instruct-2501. OpenAI. 2025. Gpt-4.1 mini.https://platform. openai.com/docs/models/gpt-4.1-mini. Vahid Sadiri Javadi, Johanne Trippas, Yash Kumar Lal, and Lucie Flek. 2025. Can stories help LLMs rea- son? curating information space through narrative. In Proceedings of the 2nd Workshop on Analogical Abstraction in Cognition, Perception, and Language (Analogy-Angle I), pages 92–107, Vienna, Austria. Association for Computational Linguistics. Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016. Improving neural machine translation models with monolingual data. In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 86–96, Berlin, Germany. Association for Computational Lin- guistics. Winston Tang. 2015. Leetcode.https://leetcode. com/. Online coding interview preparation platform. Gemma Team, Morgane Riviere, Shreya Pathak, Pier Giuseppe Sessa, Cassidy Hardin, Surya Bhupati- raju, Léonard Hussenot, Thomas Mesnard, Bobak Shahriari, Alexandre Ramé, and 1 others. 2024. Gemma 2: Improving open language models at a practical size. arXiv preprint arXiv:2408.00118. Paul H Thibodeau and Lera Boroditsky. 2011. Metaphors we think with: The role of metaphor in reasoning. PloS one, 6(2):e16782. Miles Turpin, Julian Michael, Ethan Perez, and Samuel R. Bowman. 2023. Language models don’t always say what they think: Unfaithful explanations in chain-of-thought prompting. In Thirty-seventh Conference on Neural Information Processing Sys- tems. Takahiro Ueda and AtCoder Inc. 2012. Atcoder.https: //atcoder.jp/. Online competitive programming platform. Iris Vessey. 1991. Cognitive fit: A theory-based anal- ysis of the graphs versus tables literature. Decision sciences, 22(2):219–240. Evan Z Wang, Federico Cassano, Catherine Wu, Yun- feng Bai, William Song, Vaskar Nath, Ziwen Han, Sean M. Hendryx, Summer Yue, and Hugh Zhang. 2025. Planning in natural language improves LLM search for code generation. In The Thirteenth Inter- national Conference on Learning Representations. Xuezhi Wang, Jason Wei, Dale Schuurmans, Quoc V Le, Ed H. Chi, Sharan Narang, Aakanksha Chowdhery, and Denny Zhou. 2023. Self-consistency improves chain of thought reasoning in language models. In The Eleventh International Conference on Learning Representations. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, brian ichter, Fei Xia, Ed H. Chi, Quoc V Le, and Denny Zhou. 2022. Chain of thought prompt- ing elicits reasoning in large language models. In Advances in Neural Information Processing Systems. An Yang, Baosong Yang, Beichen Zhang, Binyuan Hui, Bo Zheng, Bowen Yu, Chengyuan Li, Dayiheng Liu, Fei Huang, Haoran Wei, Huan Lin, Jian Yang, Jian- hong Tu, Jianwei Zhang, Jianxin Yang, Jiaxi Yang, Jingren Zhou, Junyang Lin, Kai Dang, and 22 oth- ers. 2024. Qwen2.5 technical report. arXiv preprint arXiv:2412.15115. ChenyangYang,YikeShi,QianouMa, Michael Xieyang Liu, Christian Kästner, and Tongshuang Wu. 2025. What prompts don’t say: Understanding and managing underspecification in llm prompts. arXiv preprint arXiv:2505.13360. Yue Zhou, Yada Zhu, Diego Antognini, Yoon Kim, and Yang Zhang. 2024. Paraphrase and solve: Exploring and exploiting the impact of surface form on math- ematical reasoning in large language models. arXiv preprint arXiv:2404.11500. Qihao Zhu, Daya Guo, Zhihong Shao, Dejian Yang, Peiyi Wang, Runxin Xu, Y Wu, Yukun Li, Huazuo Gao, Shirong Ma, and 1 others. 2024. Deepseek- coder-v2: Breaking the barrier of closed-source models in code intelligence.arXiv preprint arXiv:2406.11931. 11 Table A: Pass@10 performance of open-source solvers (f solve ) using repeated sampling (RS), narratives gener- ated by GPT-4.1-mini (G), and Claude-3.5-Haiku (C) asf narr . While the degree of improvement varies across models, performance consistently improves even whenf narr is a closed-source model other than Gemini-2.5-Flash, demonstrating the generalization of narrative reformulation across closed- and open-source models. HumanEvalLiveCodeBenchCodeForces ModelRSGCRSGCRSGC DSCoder 6.7B82.8685.7186.6722.2925.7122.2913.1213.4011.38 DSCoder V2 Lite78.1087.6290.4828.5728.5732.0025.1626.0330.05 Llama 3.1 8B79.0581.9076.1921.1425.1424.008.1113.7014.33 Gemma 2 9B 63.8167.6283.8120.0022.8622.8611.6916.0618.93 Gemma 2 27B76.1980.0087.6227.4328.0029.1422.3827.1827.24 Qwen 2.5 Coder 7B89.5288.5794.2926.8629.7129.1419.3120.6122.35 Qwen 2.5 Coder 32B92.3888.5794.2930.8634.2937.1415.0820.6122.81 Mistral Small 24B88.5787.6289.5233.7134.8634.2929.2336.0933.75 Average81.3183.4587.8626.3628.6428.8618.0121.7122.61 Appendix A Additional results A.1 Comprehensive results Generalization to other narrative generators. Table A reports additional results when GPT-4.1- mini or Claude-3.5-Haiku are used asf narr instead of Gemini-2.5-Flash, while the solver models are open-source. Similar to the main results in Table 1, we observe consistent improvements over the Re- peated Sampling (RS) prompts across open-source solvers, showing that the generalization of narrative reformulation is not limited to specific model but extends to other closed-source generators as well. Comparison of narrative-only and concatenated variants. We report pass@10 in the main paper, which aggregates performance over ten responses per problem (five variants of narrative-only and five variants of narrative concatenated with the original question). Here, we report the pass@5 results for each of the five responses in each setting individ- ually, as shown in Table B. Consequently, the RS column also reports the pass@5 score computed from five responses. As shown in the table, both the variants of narrative-only and concatenation settings consistently outperform the baseline. Sur- prisingly, we observe cases across multiple models and benchmarks where narrative-only inputs out- perform the concatenated form. This suggests that certain elements of the original problem statement may act as distractors that hinder correct reasoning or encourage spurious shortcuts, and it emphasizes the importance ofSTORYCODERin reinforcing step-by-step reasoning. Generalization to recent models. Table C re- ports pass@5 results on LiveCodeBench for three recently released models: Gemini-3.1-Flash-Lite- Preview, GPT-5.4-mini, and Claude-Sonnet-4-6. Narrative prompting consistently outperforms re- peated sampling across all three models, demon- strating that the effectiveness ofSTORYCODER generalizes to the latest models available at the time of writing, beyond those evaluated in the main experiments. A.2 Additional ablation study In the main pipeline, algorithm and genre tags serve as additional organizational cues for narrative gen- eration, and these labels operate solely within the generatorf narr , which means they play only an in- direct role in the overall problem-solving process. To isolate the effect of the structural transformation itself, we also evaluate a variant that omits these tags, which we refer to as No-Tag Narrative. The No-Tag Narrative is produced by applying the same transformation guidelines while simply removing the algorithm and genre sections. As shown in Table D, this variant still improves over the baseline and performs particularly well on eas- ier benchmarks such as HumanEval. In contrast, the full narrative tends to perform better on more challenging benchmarks, suggesting thatf narr can benefit from exploring the algorithmic and genre space when composing narratives for more com- plex problems. This pattern indicates that the pri- mary benefit comes from structural reorganization, while the auxiliary tags helpf narr better guide diffi- cult problem spaces. A.3 Comparison with other baselines To examine how different degrees of problem reformulation affect code generation, we com- pareSTORYCODERwith paraphrasing, its con- 12 Table B: Pass@5 performance of the narrative-only (Narr.) and narrative-original concatenation (Orig. + Narr.) settings. The results show consistent improvements over the baseline. For the first three closed-source models, we use the self-solving setting wheref narr = f solve . For the following eight open-source models,f narr is fixed to Gemini-2.5-Flash. HumanEvalLiveCodeBenchCodeForces ModelRS Narr. Only Orig. + Narr. RS Narr. Only Orig. + Narr. RS Narr. Only Orig. + Narr. Gemini-2.5-Flash95.9396.1996.1950.1650.8652.5752.2458.8753.59 GPT-4.1-mini95.2394.2994.2948.2253.7149.1434.6442.2735.47 Claude-3.5-Haiku 84.9787.6293.3331.9728.5734.8644.6132.4548.68 Average92.0492.7094.6043.4544.3845.5243.8344.5345.91 DSCoder 6.7B80.9581.9088.5721.1421.7125.7111.2312.3014.24 DSCoder V2 Lite 78.1087.6292.3827.4329.1433.1421.5624.6931.12 Llama 3.1 8B79.0557.1475.2420.0026.2925.717.1614.8212.30 Gemma 2 9B63.8178.1080.0020.0022.2924.0010.4216.0618.58 Gemma 2 27B76.1986.6786.6726.2929.7132.5720.9624.4026.42 Qwen 2.5 Coder 7B88.5792.3892.3825.7128.5730.8616.9620.4623.28 Qwen 2.5 Coder 32B 92.3894.2993.3329.7134.8635.4311.4624.0814.82 Mistral Small 24B86.6790.4893.3332.0032.5732.5724.8634.1233.14 Average80.7283.5787.7425.2928.1430.0015.5821.3721.74 Table C: Pass@5 performance on LiveCodeBench- v6 for latest models. Narrative prompting consistently outperforms repeated sampling (RS) across all models. ModelRS Orig. + Narr. Gemini-3.1-Flash-Lite-Preview61.1461.71 GPT-5.4-mini51.4353.71 Claude-Sonnet-4.665.1466.86 catenated variant (PC), and Story-of-Thought (SoT) (Sadiri Javadi et al., 2025) in Table E. Para- phrasing modifies only surface expressions with- out altering the underlying structure, and PC fur- ther increases input length by concatenating five paraphrases without introducing new algorithmic cues. SoT applies open-ended narrative prompting but relies on guidelines designed for knowledge- intensive multiple-choice tasks rather than algo- rithmic problem solving.Consequently, none of these methods yields consistent improvements across benchmarks, whereasSTORYCODERcon- sistently achieves the strongest performance across all benchmarks. Figure E shows that expression- level rewriting alone do not fundamentally enhance reasoning. A.4 Pass@k curves on three benchmarks Figures B and C present the pass@k curves on Hu- manEval (Chen et al., 2021), LiveCodeBench (Jain et al., 2024), and CodeForces (Mirzayanov, 2010) for closed-source and open-source models. Except for small values ofk(aroundk = 1to4), narra- tive prompting outperforms the baseline (Repeated Sampling) in all cases. Askincreases, the per- formance gains become smaller on the easier Hu- manEval benchmark, while they continue to grow on the more challenging LiveCodeBench and Code- Forces benchmarks. B Experimental details B.1 Evaluation metric The pass@kmetric evaluates the probability that at least one correct solution is obtained amongk independently sampled outputs. Formally, givenn generated outputs withccorrect ones, the expected success rate is pass@k =E " 1− n−c k n k # .(2) In code generation benchmarks, there is no sin- gle canonical solution, and multiple programs may be valid for the same problem. As a result, evalu- ation is typically performed by repeated sampling and checking whether at least one passes all test cases. This characteristic naturally motivates the use of pass@k, which measures the probability that a model produces at least one correct solution withinkattempts. Consequently, pass@khas be- come an intuitive and widely adopted metric in practice. B.2 Dataset filtering For reproducibility, we summarize the dataset fil- tering process applied to each benchmark. 13 Table D: Pass@10 Performance without algorithm or genre tags. Narr. (No-Tag) denotes the results obtained using a narrative generated without algorithm or genre tags, while Narr. denotes the tagged version used in the main pipeline. HumanEvalLiveCodeBenchCodeForces Model RS Narr. (No-Tag) Narr.RS Narr. (No-Tag) Narr.RS Narr. (No-Tag) Narr. Gemini-2.5-Flash96.1997.1496.1949.7158.2957.1460.0064.0967.55 DSCoder 6.7B82.8691.4390.4822.2924.5727.4313.1214.3618.00 DSCoder V2 Lite78.1093.3393.3328.5733.7134.2925.1636.4433.14 Llama 3.1 8B79.0588.5781.9021.1424.5727.438.1117.3119.08 Gemma 2 9B 63.8187.6282.8620.0025.1426.2911.6919.2521.39 Gemma 2 27B76.1989.5287.6227.4330.8634.2922.3829.7330.97 Qwen 2.5 Coder 7B89.5293.3393.3326.8631.4333.1419.3027.6726.74 Qwen 2.5 Coder 32B92.3895.2494.2930.8638.8640.0015.0829.2627.10 Mistral Small 24B 88.5796.1994.2933.7136.5734.8629.2341.4542.86 Average81.3191.9089.7626.3630.7132.2218.0126.9327.41 HumanEval (Chen et al., 2021). 1 We exclude sam- ples without input/output examples and standard- ize the format of all examples. Samples without reliably identifiable input/output examples (e.g., missing a function-name usage example) cannot be evaluated under our execution-based framework and are therefore excluded. Function names in sig- natures and examples are unified when they differ. After these adjustments, we obtain a filtered set of 105 samples. LiveCodeBench (Jain et al., 2024). 2 To avoid data contamination, we use the release-v6 subset that covers samples from January to April 2025. This subset consists of 112 samples from AtCoder (Ueda and Inc., 2012) and 63 from LeetCode (Tang, 2015), amounting to 175 samples. CodeForces (Mirzayanov, 2010). 3 To keep the experiment computationally feasible given that the full dataset contains more than 10,000 prob- lems, we select the tasks with moderate text length (length≤ 1000). We further exclude problems without input/output examples and retain only intermediate- and advanced-level tasks (rating≥ 2000 ). This filtering process yields a final set of 265 samples. To verify thatSTORYCODERis robust to long problem statements, we additionally conduct exper- iments on CodeForces problems with substantially longer descriptions. Keeping all other settings un- changed, we extract all samples with text length greater than 1,000 and randomly select 128 of them 1 https://github.com/openai/human-eval 2 https://github.com/LiveCodeBench/ LiveCodeBench 3 https://huggingface.co/datasets/open-r1/ codeforces to construct a subset, CodeForces-L. As shown in Table F,STORYCODERconsistently outperforms the baseline even on this long-text subset, demon- strating its robustness to the length of problem de- scriptions. B.3 Narrative transformation examples How narrative reformulation guides reasoning. Figure A shows the prompts for converting original coding questions into narrative format. Figure D provides a complete example from LiveCodeBench, including the original coding problem, its narra- tive reformulation, and the responses generated by Gemini-2.5-Flash. This example illustrates how the narrative formulation helps the model solve the problem. In this example,STORYCODERmakes the problem’s core structure (path constraints, state branching, and the global optimization objective) explicit through narrative, guiding the LLM to con- struct the correct DP state space and transition rules. The narrative elements and their correspond- ing code segments are annotated in matching col- ors, and these structural cues align the model’s reasoning to perform correct branching and global optimization, leading to the final correct solution. Intuitions behind the effectiveness of narratives. Beyond these examples, we propose the following intuitions for whySTORYCODERimproves perfor- mance: (i) Narratives align better with the pretrain- ing distribution of LLMs, which is dominated by descriptive and story-like text. Formally, letL(x) denote the average negative log-likelihood of the model on a sequencex. Since narrative text con- stitutes a substantially larger portion of pretraining corpora than code-formatted problem descriptions, we expectL(N i ) <L(Q i ), suggesting that narra- 14 Table E: Pass@10 Performance comparison of Paraphrase (Para.), Paraphrase Concatenation (PC), and Story-of- Thought (SoT) prompts. Paraphrase alters the surface expressions while preserving its meaning. PC concatenates five paraphrase variants per question to intentionally increase prompt length. SoT applies open-ended narrative prompting but relies on guidelines designed for knowledge-intensive multiple-choice tasks rather than algorithmic problem solving.STORYCODERconsistently outperforms all three methods, showing that its improvements comes from structured narrative reformulation grounded in algorithmic reasoning, rather than surface-level expression changes, increased input length, or task-agnostic narrative guidelines. HumanEvalLiveCodeBenchCodeForces ModelPara.PCSoTNarr.Para.PCSoTNarr.Para.PCSoTNarr. Gemini-2.5-Flash94.29 93.07 94.29 96.1950.29 50.29 50.86 57.1450.51 51.55 61.86 67.55 DSCoder 6.7B81.90 85.15 87.62 90.4824.00 24.00 26.29 27.4311.67 13.90 16.10 18.01 DSCoder V2 Lite 85.71 88.12 90.48 93.3328.57 30.29 28.00 34.2926.40 27.67 31.40 33.14 Llama 3.1 8B83.81 86.14 86.67 81.9022.86 24.57 28.57 27.437.6213.70 18.26 19.08 Gemma 2 9B68.57 70.30 80.95 82.8620.57 20.00 22.86 26.2913.40 14.04 16.76 21.39 Gemma 2 27B81.90 79.21 84.76 87.6227.43 26.29 28.00 34.2922.49 21.42 26.92 30.97 Qwen 2.5 Coder 7B88.57 88.12 92.38 93.3326.86 28.57 32.00 33.1423.28 25.59 25.01 26.74 Qwen 2.5 Coder 32B 92.38 91.09 93.33 94.2934.29 33.71 38.29 40.0019.63 17.60 33.03 27.10 Mistral Small 24B87.62 90.10 92.38 94.2933.14 33.71 34.86 34.8629.53 34.24 40.78 42.87 Average83.8184.7888.5789.7627.2227.6429.8632.2219.2521.0226.0327.41 Table F: Pass@10 performance on CodeForces-L (longer descriptions). The table reports results where f narr is fixed to Gemini-2.5-Flash andf solve varies by row. Narrative prompting consistently outperforms the baseline across subsets with longer problem lengths. CodeForces-L ModelRSNarr. Gemini-2.5-Flash35.9453.91 DSCoder 6.7B1.567.03 DSCoder V2 Lite8.5918.75 Llama 3.1 8B0.03.12 Gemma 2 9B2.347.81 Gemma 2 27B 11.7214.06 Qwen 2.5 Coder 7B7.8110.94 Qwen 2.5 Coder 32B9.3816.41 Mistral Small 24B12.520.31 Average6.7412.30 tive reformulation acts as a bridge connecting broad linguistic knowledge from pretraining to coding tasks. This is consistent with our empirical find- ings across 11 models; (i) Narratives reorganize the problem into a clearer, more solvable struc- ture by turning scattered constraints and abstract rules into a grounded, interpretable description that helps the model identify the appropriate algorith- mic pattern; (i) Narratives induce a more linear and model-friendly reasoning flow by outlining a natural step-by-step progression and reducing the model’s tendency to take incorrect shortcuts during implementation. B.4 Narrative validity filtering In Section 4.2, all three closed-source models gen- erate valid narratives that satisfy the required for- mat with 100% accuracy. However, we observe that open-source models occasionally fail to pro- duce valid narrative texts, which we attribute to limited instruction-following capabilities in smaller models. To ensure a fair and reliable evaluation, we apply the following filtering criteria: narrative outputs are considered invalid if (i) the sequence length is fewer than 50 tokens (near-empty con- tent), or (i) the sequence length exceeds 99% of the model’s maximum generation limit, which cor- responds to degenerate token repetition, or (i) the output lacks the required components (task overview, constraints, and input/output format). Il- lustrative examples of each invalid type are pro- vided in Table H. B.5 Misaligned genres To construct the misalignment setting, we curated a set of genres that are intentionally incongruent with problem descriptions. These genres were se- lected to represent contexts that are stylistically or semantically distant from typical programming tasks, ensuring that the resulting narratives do not naturally align with the problem’s intent. Table G presents the complete list of misaligned genres, grouped into four categories. C The use of LLMs We used LLMs only for minor language editing, including adjustments to word choices and clar- ity. LLMs were not used for the research design, analysis, interpretation, or manuscript preparation. 15 Table G: Complete list of misaligned genres grouped into four categories. CategoryMisaligned Genres Practical / Administrative Documents Hospital Intake Form; Medical Prescription Form; Personal Information Consent Form; Insurance Claim Form; Visa Application Form; Tax Return Form Legal / Public Records Court Transcript of an Extortion Case; Heavy Machinery Operator License; Military Service Exemption Certificate; Divorce Decree; Bank Loan Agreement Industrial / Media Contexts Billboard Advertisement for a Toothbrush; Radio Weather Fore- cast; Model Agency Contract Funerary / Ritual Records Funeral Service Program; Memorial Tribute Writing; Obituary Column; Eulogy; Gravestone Inscription; Condolence Letter Table H: Examples of invalid narratives generated by Llama 3.1 8B Instruct, Gemma 2 9B Instruct, and DeepSeek V2 Lite Chat, in table order. Invalid narrative types: (i) Incomplete Output: too short to construct a narrative; (i) Repetitive Output: filled with meaningless repetition; (i) Missing Components: lacking the three required components (task overview, constraints, and input/output format). Invalid TypeGenerated Text Incomplete Output “return [x for x in l if x > 0] **Please note:** This is a formatted list, but the narrative should not mention \"formatted list\" or any specific format. - Algorithm Category: - Narrative Genre: - Task Overview: - Constraints: - Example Input/Output:” Repetitive Output “Here’s the conversion to a narrative format: - Algorithm Category: Dynamic Programming - Narrative Genre: Mysterious Archaeology - Task Overview: In the heart of the mystical Amazon, an ancient temple holds secrets of the past. Your mission as a brilliant archaeologist is to uncover the temple’s treasure, guarded by the mysterious priestesses. (omitted) Conversely, when your opponent has a set of pieces including a 5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10, the king’s value is 123. — is the transformed narrative in the specified format. — is the transformed narrative in the format you requested. — is the transformed narrative in the specified format. — is the transformed narrative in the format you requested. — is the transformed narrative in the specified format. — is the transformed narrative in the format you requested. ... (omitted)” Missing Required Components “Explanation 1. To solve this task it’s best to think in terms of a small internal state we carry around, which changes depending on which operation we’re considering. 2. Initially, all 1s are at the beginning of the string and all 0s at the end, so we can choose the entire string and get the answer we desire. 3. After the first operation, we would get the string 01111011, but if we look at the answer state we had previously, we see that we had 1110100 at the end, which is shorter. So we revert the last operation and pick the next substring of 01111, and repeat the process. 4. After the second operation, the answer state would become 11000010, which is still worse than our previous internal state. So we go back one more step and choose the entire string again, finally resulting in 010110. 5. Applying the steps to the other test cases follows a very similar logic, making use of the internal state to make decisions and progress.” 16 Narrative Transformation Guidelines Please transform the coding problem into a narrative story using the following guidelines. ### Guidelines for Narrative Conversion: Before writing the narrative, you must complete two preliminary steps: 1. Review the major categories of coding test algorithms: - Graph Algorithms - Dynamic Programming - Greedy Algorithms - Sorting and Searching - String Algorithms - Data Structures - Mathematics and Number Theory - Simulation and Implementation 2. Decide which algorithm category the given problem most closely belongs to. Then, select a narrative genre that naturally aligns with the chosen algorithm. ### Output Format: You must write the output in the exact following order with the specified headers: - Algorithm Category: (one of the categories above) - Narrative Genre: (a fitting genre of your choice) - Task Overview: Describe the background and objective of the problem in a clear, narrative- inspired manner. The selected algorithm should be introduced naturally here, with its logic explained as part of the setting or scenario. - Constraints: State input sizes, value ranges, conditions, and key operational rules. If efficiency or time limits exist, express them as natural constraints. The chosen algorithm should also shape these rules. - Example Input/Output: Reframe the examples as part of the scenario’s flow. Present them as clear, contextual situations. The narrative must include all essential parts of the original problem, ensuring no constraints, goals, or examples are omitted. Do not include any other text outside these five sections. Do not attempt to solve the problem or provide any code. Your task is only to transform the problem statement into the narrative format as specified. ### The coding problem is as follows: Coding Problem Figure A: Instructions for converting a code generation benchmark question into a narrative format. 17 (a) Gemini-2.5-Flash (b) ChatGPT-4.1-mini (c) Claude-3.5-Haiku Figure B: Pass@k performance of closed-source models fork = 1, . . . , 10. Except for ChatGPT-4.1-mini on HumanEval, narrative prompting consistently outperforms the baseline askincreases across all models and benchmarks. 18 Figure C: Pass@k performance of open-source models fork = 1, . . . , 10. Across all models and benchmarks, narrative prompting consistently outperforms the baseline as k increases. 19 Original Question Narrative Reformulation (a) Original Prompt (Top) and Narrative Reformulation (Bottom) Task Overview: In the year 2342, Earth lies fragmented, its surface scarred by the Great Cataclysm. Humanity survives in isolated pockets, relying on ancient, automated mining units to retrieve precious resources from the irradiated ruins. You are tasked with programming the "Pathfinder Unit 7," a sophisticated autonomous robot designed for high-risk recovery missions. Its current assignment: navigate the treacherous Grid Sector Alpha-9. This sector is a vast, decaying urban labyrinth, represented as an `m x n` grid. Each cell within this grid may contain valuable "Aetherium Crystals" (positive coin values) or be infested by "Scavenger Bots" (negative coin values). Aetherium Crystals boost the Pathfinder's energy reserves, while Scavenger Bots drain them by an equivalent amount. The Pathfinder must journey from its deployment point, the top-left corner (0, 0) of the sector, to the designated extraction zone at the bottom-right corner (`m -1, n -1`). Due to its robust maneuvering system, the Pathfinder can only move directly "South" or "East" from its current position.A critical feature of Pathfinder Unit 7 is its limited "Disruptor Field" capability, which can neutralize the energy-draining effects of up to two Scavenger Bots encountered along its path. Your mission, should you choose to accept it, is to chart a course for Pathfinder Unit 7 that maximizes its net Aetherium gain upon reaching the extraction zone. The core challenge is to strategically utilize the Disruptor Fields to avoid costly encounters, effectively making optimal choices at each step, a classic dynamic programming puzzle. Constraints: The Grid Sector Alpha-9 is quite expansive, with its dimensions (`m` rows and `n` columns) ranging from `1` to `500` units. The Aetherium Crystal deposits or Scavenger Bot energy drains in any given cell `[i][j]` can vary widely, from a drain of `1000` units to a gain of `1000` units. Even after utilizing its Disruptor Fields, Pathfinder Unit 7’s total Aetherium balance can dip into the negative, indicating a significant energy debt. The mission's success is measured purely by the final net Aetherium count. Example Input/Output: Example 1: Pathfinder Unit 7's Aetherium Scanner reports the following for a small 3x3 section of Grid Sector Alpha-9: Input (Aetherium Map): [[0,1,-1], [1,-2,3], [2,-3,4]] After careful computation, the optimal trajectory for Pathfinder Unit 7, maximizing its Aetherium gain, is identified. Output (Max Aetherium Gain): 8 Detailed Trajectory Analysis: -Deployment at (0, 0): Initial energy reserves are 0 Aetherium. -Move to (0, 1): Aetherium gain of 1. Total reserves: 1. -Move to (1, 1): A Scavenger Bot is detected, threatening to drain 2 Aetherium. Pathfinder Unit 7 activates one Disruptor Field, neutralizing the threat. Total reserves remain: 1. -Move to (1, 2): Aetherium gain of 3. Total reserves: 4. -Move to (2, 2): Aetherium gain of 4. Total reserves: 8. Extraction successful with 8 Aetherium. Example 2: Another mission involves a smaller, 2x3 Grid Sector Beta-7, known for its rich, unmolested Aetherium veins. Input (Aetherium Map): [[10,10,10], [10,10,10]] The computed optimal path for Pathfinder Unit 7 in this sector yields a high Aetherium return. Output (Max Aetherium Gain): 40 Detailed Trajectory Analysis: -Deployment at (0, 0): Initial energy reserves are 10 Aetherium. -Move to (0, 1): Aetherium gain of 10. Total reserves: 20. -Move to (0, 2): Aetherium gain of 10. Total reserves: 30. -Move to (1, 2): Aetherium gain of 10. Total reserves: 40. Extraction successful with 40 Aetherium. No Scavenger Bots were encountered, so Disruptor Fields remained unused. import collections class Solution: def maximumAmount(self, coins: List[List[int]]) -> int: m = len(coins) n = len(coins[0]) # dp[r][c][k] stores the maximum Aetherium gain to reach (r, c) # using k disruptor fields. # k can be 0, 1, or 2. dp = # Initialize dp table with a very small number # Using a dictionary to store only reachable states # dp[(r, c, k)] = value # Base case: starting point (0, 0) # If coins[0][0] is negative, we might use a disruptor field. if coins[0][0] < 0: dp[(0, 0, 1)] = 0 # Used 1 disruptor field dp[(0, 0, 0)] = coins[0][0] # Did not use disruptor field else: dp[(0, 0, 0)] = coins[0][0] q = collections.deque([(0, 0, 0), (0, 0, 1)]) # (r, c, k) visited = set() if (0,0,0) in dp: visited.add((0,0,0)) if (0,0,1) in dp: visited.add((0,0,1)) for r in range(m): for c in range(n): for k in range(3): # k = 0, 1, 2 if (r, c, k) not in dp: dp[(r, c, k)] = -float('inf') # Iterate through the grid for r in range(m): for c in range(n): current_coin = coins[r][c] # Consider coming from (r-1, c) (South) if r > 0: for k_prev in range(3): if dp[(r -1, c, k_prev)] != -float('inf'): # Option 1: Don't use disruptor field new_k = k_prev new_val = dp[(r -1, c, k_prev)] + current_coin dp[(r, c, new_k)] = max(dp[(r, c, new_k)], new_val) # Option 2: Use disruptor field if current_coin # is negative and k_prev < 2 if current_coin < 0 and k_prev < 2: new_k = k_prev + 1 new_val = dp[(r -1, c, k_prev)] dp[(r, c, new_k)] = max(dp[(r, c, new_k)], new_val) # Consider coming from (r, c-1) (East) if c > 0: for k_prev in range(3): if dp[(r, c -1, k_prev)] != -float('inf'): # Option 1: Don't use disruptor field new_k = k_prev new_val = dp[(r, c -1, k_prev)] + current_coin dp[(r, c, new_k)] = max(dp[(r, c, new_k)], new_val) # Option 2: Use disruptor field if current_coin # is negative and k_prev < 2 if current_coin < 0 and k_prev < 2: new_k = k_prev + 1 new_val = dp[(r, c -1, k_prev)] dp[(r, c, new_k)] = max(dp[(r, c, new_k)], new_val) max_aetherium = -float('inf') for k in range(3): max_aetherium = max(max_aetherium, dp[(m -1, n -1, k)]) return max_aetherium import math class Solution: def maximumAmount(self, coins: List[List[int]]) -> int: m = len(coins) n = len(coins[0]) dp = def solve(r, c, k): if r == m -1 and c == n -1: return coins[r][c] if coins[r][c] >= 0 or k > 0 else coins[r][c] if (r, c, k) in dp: return dp[(r, c, k)] current_coins = coins[r][c] val_with_neutralize = -math.inf if current_coins < 0 and k > 0: val_with_neutralize = current_coins * -1 if r + 1 < m: val_with_neutralize = max( val_with_neutralize, current_coins * -1 + solve(r + 1, c, k -1) ) if c + 1 < n: val_with_neutralize = max( val_with_neutralize, current_coins * -1 + solve(r, c + 1, k -1) ) val_without_neutralize = current_coins if r + 1 < m: val_without_neutralize = max( val_without_neutralize, current_coins + solve(r + 1, c, k) ) if c + 1 < n: val_without_neutralize = max( val_without_neutralize, current_coins + solve(r, c + 1, k) ) if current_coins >= 0: dp[(r, c, k)] = val_without_neutralize else: dp[(r, c, k)] = max(val_with_neutralize, val_without_neutralize) return dp[(r, c, k)] return solve(0, 0, 2) You are given an m x n grid. A robot starts at the top-left corner of the grid (0, 0) and wants to reach the bottom-right corner (m -1, n -1). The robot can move either right or down at any point in time. The grid contains a value coins[i][j] in each cell: If coins[i][j] >= 0, the robot gains that many coins. If coins[i][j] < 0, the robot encounters a robber, and the robber steals the absolute value of coins[i][j] coins. The robot has a special ability to neutralize robbers in at most 2 cells on its path, preventing them from stealing coins in those cells. Note: The robot's total coins can be negative. Return the maximum profit the robot can gain on the route. Example 1: Input: coins = [[0,1,-1],[1,-2,3],[2,-3,4]] Output: 8 Explanation: An optimal path for maximum coins is: Start at (0, 0) with 0 coins (total coins = 0). Move to (0, 1), gaining 1 coin (total coins = 0 + 1 = 1). Move to (1, 1), where there's a robber stealing 2 coins. The robot uses one neutralization here, avoiding the robbery (total coins = 1). Move to (1, 2), gaining 3 coins (total coins = 1 + 3 = 4). Move to (2, 2), gaining 4 coins (total coins = 4 + 4 = 8). Example 2: Input: coins = [[10,10,10],[10,10,10]] Output: 40 Explanation: An optimal path for maximum coins is: Start at (0, 0) with 10 coins (total coins = 10). Move to (0, 1), gaining 10 coins (total coins = 10 + 10 = 20). Move to (0, 2), gaining another 10 coins (total coins = 20 + 10 = 30). Move to (1, 2), gaining the final 10 coins (total coins = 30 + 10 = 40). Constraints: m == coins.length n == coins[i].length 1 <= m, n <= 500 -1000 <= coins[i][j] <= 1000 ✗ ✓ (Incorrect) (Correct) (b) Model Responses Figure D: A complete example of a narrative reformulation (f narr = f solve =Gemini-2.5-Flash), wheref solve correctly implements the intended dynamic programming specification. 20 Original Question Paraphrasing (a) Original Prompt (Top) and Paraphrased Prompt (Bottom) (b) Model Responses A robot is situated on a grid of dimensions m x n. Its journey begins at the top-left cell (0, 0) and its destination is the bottom-right cell (m -1, n -1). The robot is restricted to moving only right or down in each step. Each cell (i, j) on the grid contains a value, `coins[i][j]`, which affects the robot's total earnings: * If `coins[i][j]` is non-negative, the robot collects that many coins. * If `coins[i][j]` is negative, a robber is present, and the robot loses the absolute value of `coins[i][j]` coins. The robot possesses a unique ability: it can choose to "neutralize" up to 2 cells on its chosen path where robbers are present. When a robber is neutralized, the robot avoids losing any coins in that particular cell. It's important to note that the robot's total coin count can become negative. The objective is to determine the highest possible total coin amount the robot can accumulate by the time it reaches the bottom-right corner. Example 1: Input: coins = [[0,1,-1],[1,-2,3],[2,-3,4]] Output: 8 Explanation: One path that yields the maximum coins is as follows: The robot starts at (0, 0) with 0 coins (current total = 0). Moves to (0, 1), earning 1 coin (current total = 0 + 1 = 1). Moves to (1, 1), where a robber would steal 2 coins. The robot uses one neutralization here, preventing the loss of coins (current total = 1). Moves to (1, 2), earning 3 coins (current total = 1 + 3 = 4). Moves to (2, 2), earning 4 coins (current total = 4 + 4 = 8). Example 2: Input: coins = [[10,10,10],[10,10,10]] Output: 40 Explanation: One path that yields the maximum coins is as follows: The robot starts at (0, 0), earning 10 coins (current total = 10). Moves to (0, 1), earning 10 coins (current total = 10 + 10 = 20). Moves to (0, 2), earning another 10 coins (current total = 20 + 10 = 30). Moves to (1, 2), earning the final 10 coins (current total = 30 + 10 = 40). Constraints: m == coins.length n == coins[i].length 1 <= m, n <= 500 -1000 <= coins[i][j] <= 1000 import math class Solution: def maximumAmount(self, coins: List[List[int]]) -> int: m = len(coins) n = len(coins[0]) dp = def solve(r, c, k): if r == m -1 and c == n -1: return coins[r][c] if coins[r][c] >= 0 or k > 0 else coins[r][c] if (r, c, k) in dp: return dp[(r, c, k)] current_coins = coins[r][c] val_if_neutralized = -math.inf if current_coins < 0 and k > 0: val_if_neutralized = solve(r, c, k -1) -current_coins res = -math.inf if r + 1 < m: next_val = solve(r + 1, c, k) res = max(res, next_val) if c + 1 < n: next_val = solve(r, c + 1, k) res = max(res, next_val) if current_coins < 0 and k > 0: dp[(r, c, k)] = max(res + current_coins, val_if_neutralized) else: dp[(r, c, k)] = res + current_coins return dp[(r, c, k)] return solve(0, 0, 2) import math class Solution: def maximumAmount(self, coins: List[List[int]]) -> int: m = len(coins) n = len(coins[0]) dp = def solve(r, c, k): if r == m -1 and c == n -1: return coins[r][c] if coins[r][c] >= 0 or k > 0 else coins[r][c] if (r, c, k) in dp: return dp[(r, c, k)] current_coins = coins[r][c] val_with_neutralize = -math.inf if current_coins < 0 and k > 0: val_with_neutralize = current_coins * -1 if r + 1 < m: val_with_neutralize = max( val_with_neutralize, current_coins * -1 + solve(r + 1, c, k -1) ) if c + 1 < n: val_with_neutralize = max( val_with_neutralize, current_coins * -1 + solve(r, c + 1, k -1) ) val_without_neutralize = current_coins if r + 1 < m: val_without_neutralize = max( val_without_neutralize, current_coins + solve(r + 1, c, k) ) if c + 1 < n: val_without_neutralize = max( val_without_neutralize, current_coins + solve(r, c + 1, k) ) if current_coins >= 0: dp[(r, c, k)] = val_without_neutralize else: dp[(r, c, k)] = max(val_with_neutralize, val_without_neutralize) return dp[(r, c, k)] return solve(0, 0, 2) You are given an m x n grid. A robot starts at the top-left corner of the grid (0, 0) and wants to reach the bottom-right corner (m -1, n -1). The robot can move either right or down at any point in time. The grid contains a value coins[i][j] in each cell: If coins[i][j] >= 0, the robot gains that many coins. If coins[i][j] < 0, the robot encounters a robber, and the robber steals the absolute value of coins[i][j] coins. The robot has a special ability to neutralize robbers in at most 2 cells on its path, preventing them from stealing coins in those cells. Note: The robot's total coins can be negative. Return the maximum profit the robot can gain on the route. Example 1: Input: coins = [[0,1,-1],[1,-2,3],[2,-3,4]] Output: 8 Explanation: An optimal path for maximum coins is: Start at (0, 0) with 0 coins (total coins = 0). Move to (0, 1), gaining 1 coin (total coins = 0 + 1 = 1). Move to (1, 1), where there's a robber stealing 2 coins. The robot uses one neutralization here, avoiding the robbery (total coins = 1). Move to (1, 2), gaining 3 coins (total coins = 1 + 3 = 4). Move to (2, 2), gaining 4 coins (total coins = 4 + 4 = 8). Example 2: Input: coins = [[10,10,10],[10,10,10]] Output: 40 Explanation: An optimal path for maximum coins is: Start at (0, 0) with 10 coins (total coins = 10). Move to (0, 1), gaining 10 coins (total coins = 10 + 10 = 20). Move to (0, 2), gaining another 10 coins (total coins = 20 + 10 = 30). Move to (1, 2), gaining the final 10 coins (total coins = 30 + 10 = 40). Constraints: m == coins.length n == coins[i].length 1 <= m, n <= 500 -1000 <= coins[i][j] <= 1000 ✗ (Incorrect) ✗ (Incorrect) Figure E: Paraphrasing example. Both the paraphrase and the solution were generated by Gemini-2.5-Flash. Unlike the narrative transformation in Figure D, paraphrasing modifies only the surface wording while preserving the original structure, so it does not lead the model to think in a different way, which is whatSTORYCODERachieves. 21