13. Nth Fibonacci Number
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I use an iterative approach to calculate the nth Fibonacci number. I maintain two variables, secondLast
and last
, to keep track of the last two Fibonacci numbers. I iterate n-1
times to calculate the nth Fibonacci number.
Initialize the 1st Fibonacci number to 0 using the variable secondLast
, and the 2nd Fibonacci number to 1 using last
variable.
Proceed with a loop for the remaining n-1
iterations, updating curr
as the sum of secondLast
and last
. Subsequently, shift the value of last
to secondLast
, and assign the value of curr
to last
for the upcoming iterations.
Let's take an example where n
is 5.
So, the 5th Fibonacci number is 5.
Time Complexity: The loop runs for n-1
iterations, resulting in a linear time complexity of O(n)
.
Auxiliary Space Complexity: The algorithm uses a constant amount of extra space, resulting in an auxiliary space complexity of O(1)
.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the repository.