Problem Statement
Calculate the N-th Fibonacci number using an iterative approach. The Fibonacci sequence is defined as:
[ F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) , ext{for} , n > 1. ]
Example
-
Input: n = 5
Output: 5
Explanation: The Fibonacci sequence is 0, 1, 1, 2, 3, 5, ....
-
Input: n = 10
Output: 55
Explanation: The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ....
Brute Force Approach
Approach
Idea: Use an iterative approach to calculate the Fibonacci sequence up to the N-th number. Use an array to store all Fibonacci numbers.
Steps
- Handle the base cases for
n = 0 and n = 1. Return 0 and 1, respectively.
- Initialize an array to store the Fibonacci sequence.
- Populate the array by iterating from
2 to n, calculating each Fibonacci number as the sum of the previous two numbers.
- Return the N-th Fibonacci number from the array.
Time & Space Complexity
- Time Complexity: O(n)
- The loop runs
n iterations to calculate the Fibonacci sequence.
- Space Complexity: O(n)
- An array of size
n is used to store Fibonacci numbers.
Code Snippet
Dry Run
Input: n = 5
- Initialize
fib = [0, 1].
- Loop through to populate
fib:
fib[2] = fib[1] + fib[0] = 1 + 0 = 1.
fib[3] = fib[2] + fib[1] = 1 + 1 = 2.
fib[4] = fib[3] + fib[2] = 2 + 1 = 3.
fib[5] = fib[4] + fib[3] = 3 + 2 = 5.
- Return
fib[5] = 5.
Efficient Approach
Approach
Idea: Instead of storing all Fibonacci numbers, maintain only the last two numbers of the sequence to reduce space usage.
Steps
- Handle the base cases for
n = 0 and n = 1. Return 0 and 1, respectively.
- Initialize two variables,
prev1 and prev2, to store the last two Fibonacci numbers.
- Iterate from
2 to n, updating the variables to calculate the next Fibonacci number.
- Return the final value of
prev1, which will hold the N-th Fibonacci number.
Time & Space Complexity
- Time Complexity: O(n)
- The loop runs
n iterations to calculate the Fibonacci sequence.
- Space Complexity: O(1)
- Only two variables are used, regardless of
n.
Code Snippet