TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
Groot grows according to a pattern similar to the Fibonacci sequence. Given n
, find the height of Groot after n
months using a recursive method.
The Fibonacci numbers, commonly denoted F(n)
, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
n
months using the Fibonacci sequence.n
?
n = 0
and n = 1
.HAPPY CASE
Input: 5
Output: 5
Explanation: The 5th Fibonacci number is 5.
Input: 8
Output: 21
Explanation: The 8th Fibonacci number is 21.
EDGE CASE
Input: 0
Output: 0
Explanation: The 0th Fibonacci number is 0.
Input: 1
Output: 1
Explanation: The 1st Fibonacci number is 1.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Recursive Fibonacci Problems, we want to consider the following approaches:
n = 0
and n = 1
.Plan the solution with appropriate visualizations and pseudocode.
General Idea:
n
. Define the base cases for n = 0
and n = 1
.Recursive Approach:
1) Base case: If `n` is 0, return 0.
2) Base case: If `n` is 1, return 1.
3) Recursive case: Return the sum of `fibonacci_growth(n - 1)` and `fibonacci_growth(n - 2)`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def fibonacci_growth(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_growth(n - 1) + fibonacci_growth(n - 2)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
fibonacci_growth
function with the input 5
. The function should return 5 after calculating fibonacci_growth(4)
and fibonacci_growth(3)
recursively.8
. The function should return 21 after recursively calculating fibonacci_growth(7)
and fibonacci_growth(6)
.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(2^N)
where N
is the input n
. The function makes two recursive calls for each non-base case, leading to exponential growth in the number of calls.O(N)
due to the recursion stack. The depth of the recursion is proportional to n
, leading to linear space usage.