Log In Sign Up
Day 31

Day 31: Fibonacci Sequence and Dynamic Programming

31/60 Days

Fibonacci Sequence and Dynamic Programming #

Welcome to Day 31 of our 60 Days of Coding Algorithm Challenge! Today, we’ll dive deeper into Dynamic Programming by exploring the Fibonacci sequence, a classic problem that demonstrates the power of DP.

The Fibonacci Sequence #

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It typically starts with 0 and 1, and the sequence goes as follows:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Mathematically, it can be defined as:

F(n) = F(n-1) + F(n-2), where F(0) = 0 and F(1) = 1

Naive Recursive Approach #

Let’s start with a naive recursive implementation:

1def fibonacci_naive(n):
2    if n <= 1:
3        return n
4    return fibonacci_naive(n-1) + fibonacci_naive(n-2)
5
6# Example usage
7print(fibonacci_naive(10))  # Output: 55

While this implementation is simple and intuitive, it has a time complexity of O(2^n), making it extremely inefficient for large values of n.

Dynamic Programming Approaches #

We can significantly improve the efficiency using Dynamic Programming. Let’s explore both top-down (memoization) and bottom-up (tabulation) …