Fibonacci Number – Solution & Complexity
1. Understand the Sequence
- Fibonacci starts with
F(0) = 0andF(1) = 1. - Every later value is the sum of the two previous values.
- The input
nasks for the 0-indexed valueF(n).
2. Recursive Definition
- The formula naturally translates into recursion.
- However, plain recursion recomputes the same values many times.
- That makes it exponential and too slow for larger
n.
3. Keep Only the Last Two Values
- To compute the next Fibonacci number, we only need the previous two.
- Store them as
aandb, representing consecutive Fibonacci values. - Repeatedly advance the pair until
areachesF(n).
4. Iterate Up to n
- Start with
a = 0andb = 1. - Each loop moves from
(F(i), F(i+1))to(F(i+1), F(i+2)). - After
nmoves,ais the desired answer.
5. Final Solution and Complexity
- The iterative solution avoids repeated work.
- Time complexity is O(n).
- Space complexity is O(1) because it stores only two integers.