From b36e23d095141ab75a173b7a52e666e6b21786a3 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Sat, 17 Jan 2026 00:17:32 +0000 Subject: [PATCH] Optimize fibonacci **Optimization Explanation:** I replaced the naive exponential recursion with a memoized recursion using a Map to cache previously computed results. This preserves the original function signature and exact behavior (including handling of non-integer inputs) while reducing the runtime from O(phi^n) to O(k) where k is the number of distinct subproblems encountered. Using Map reduces repeated computations and memory churn without changing recursion depth or error characteristics. --- code_to_optimize_js/fibonacci.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/code_to_optimize_js/fibonacci.js b/code_to_optimize_js/fibonacci.js index b0ab2b51c..701ad1c88 100644 --- a/code_to_optimize_js/fibonacci.js +++ b/code_to_optimize_js/fibonacci.js @@ -9,10 +9,20 @@ * @returns {number} - The nth Fibonacci number */ function fibonacci(n) { - if (n <= 1) { - return n; + const cache = new Map(); + function fib(x) { + if (x <= 1) { + return x; + } + const cached = cache.get(x); + if (cached !== undefined) { + return cached; + } + const result = fib(x - 1) + fib(x - 2); + cache.set(x, result); + return result; } - return fibonacci(n - 1) + fibonacci(n - 2); + return fib(n); } /**