⚡️ Speed up function fibonacci by 15.63%#314
Open
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Open
Conversation
The recursive `fibonacci` function was replaced with an iterative bottom-up approach that tracks only the two most recent values (`prev2`, `prev1`) in a single forward pass, eliminating the exponential call tree that recomputes the same subproblems thousands of times. For example, computing `fibonacci(18)` originally requires ~4,000+ recursive calls with deep stack overhead, while the optimized version completes in exactly 17 loop iterations with O(1) space. This yields a 15% runtime improvement across the test suite, which exercises inputs from 0 to 18, with no correctness regressions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📄 15.63% (0.16x) speedup for
fibonacciinsrc/algorithms/dynamic_programming.py⏱️ Runtime :
8.93 milliseconds→7.72 milliseconds(best of161runs)📝 Explanation and details
The recursive
fibonaccifunction was replaced with an iterative bottom-up approach that tracks only the two most recent values (prev2,prev1) in a single forward pass, eliminating the exponential call tree that recomputes the same subproblems thousands of times. For example, computingfibonacci(18)originally requires ~4,000+ recursive calls with deep stack overhead, while the optimized version completes in exactly 17 loop iterations with O(1) space. This yields a 15% runtime improvement across the test suite, which exercises inputs from 0 to 18, with no correctness regressions.✅ Correctness verification report:
To edit these changes
git checkout codeflash/optimize-fibonacci-mo973r8dand push.