Search⌘ K
AI Features

Solution Review: Corresponding Fibonacci Number

Explore the solutions to the Fibonacci number problem by understanding both iterative and recursive approaches. Learn how iteration tracks previous elements efficiently while recursion uses function calls with base cases and recursive steps. This lesson helps you understand and implement these methods to solve Fibonacci sequence problems in coding interviews.

Solution #1: Iterative Method

Python 3.5
def fibonacci(testVariable):
fn0 = 0
fn1 = 1
for i in range(0, testVariable):
temp = fn0 + fn1
# Setting variables for next iteration
fn0 = fn1
fn1 = temp
return fn0
# Driver Code
testVariable = 7
print(fibonacci(testVariable))

Explanation

In the iterative method, we keep track of the two previous elements using the variables fn0 and fn1. Initially, the values of the two variables are:

fn0 = 0
fn1 = 1

However, with each iteration, the values are updated as follows:

Solution #2: Recursive Method

Python 3.5
def fibonacci(testVariable):
# Base Case
if testVariable <= 1 :
return testVariable
# Recursive Case
return(fibonacci(testVariable - 1) + fibonacci(testVariable - 2))
# Driver Code
testVariable = 7
print(fibonacci(testVariable))

Explanation:

In the code above, the function fibonacci() is a recursive function, since it calls itself in the function body.

The base case of the function (line number 3) deals with the two initial values: for index 00 ...