From 3681a1b7d4690408a2adfe2ce48397fc71ef26b3 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 16 Jan 2026 20:21:06 +0000 Subject: [PATCH] Optimize fibonacci MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The optimized code applies **memoization** to eliminate redundant recursive calls, dramatically reducing time complexity from exponential O(φ^n) ≈ O(1.618^n) to linear O(n). **Key Changes:** - Added a `Map`-based cache to store previously computed Fibonacci values - Each result is computed once and retrieved from cache on subsequent calls - Cache lookups occur before recursion, short-circuiting expensive recomputation **Why This Is Faster:** The naive recursive implementation recomputes the same Fibonacci values exponentially many times. For example, `fibonacci(30)` triggers over 2.6 million recursive calls. With memoization, each value from 0 to n is computed exactly once, reducing 30 calls to just 31 cache operations—a fundamental algorithmic improvement that scales exponentially better. **Performance Impact:** - The **1,298x speedup** (8.55ms → 6.58μs) reflects this exponential → linear transformation - For `fibonacci(30)`, the test completes well under the 2000ms threshold (vs. potentially minutes without caching) - Sequential and repeated calls benefit immensely—once cached, lookups are O(1) - The optimization shines for inputs ≥15 where naive recursion becomes noticeably slow **Test Case Analysis:** - **Small inputs (n ≤ 10)**: Minimal difference, but still faster due to cache hits on repeated calls - **Medium inputs (n = 15-25)**: Major gains; tests that check recurrence relations (`fibonacci(n-1) + fibonacci(n-2)`) benefit from overlapping subproblems being cached - **Large inputs (n = 30)**: Transforms impractical runtime into microseconds - **Repeated calls**: Determinism tests see instant O(1) retrieval after first computation The cache persists across function calls, making this optimization especially valuable in workloads with repeated or sequential Fibonacci queries. --- code_to_optimize_js/fibonacci.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/code_to_optimize_js/fibonacci.js b/code_to_optimize_js/fibonacci.js index b0ab2b51c..05662900e 100644 --- a/code_to_optimize_js/fibonacci.js +++ b/code_to_optimize_js/fibonacci.js @@ -8,11 +8,19 @@ * @param {number} n - The index of the Fibonacci number to calculate * @returns {number} - The nth Fibonacci number */ +const cache = new Map(); + function fibonacci(n) { + if (cache.has(n)) return cache.get(n); if (n <= 1) { + cache.set(n, n); return n; } - return fibonacci(n - 1) + fibonacci(n - 2); + const a = fibonacci(n - 1); + const b = fibonacci(n - 2); + const res = a + b; + cache.set(n, res); + return res; } /**