Dynamic Programming Explained – A Beginner’s Guide with Python
DEV Community

Dynamic Programming Explained - A Beginner’s Guide with Python

Have you ever written a program that solves the same problem again and again? Imagine calculating the Fibonacci sequence using recursion. Although the code looks simple, it can become surprisingly slow as the input increases.

This is where Dynamic Programming (DP) comes in. It is a powerful algorithmic technique that improves efficiency by storing the results of smaller problems and reusing them instead of repeating calculations. In this guide, we will explore how dynamic programming works, understand its two main approaches, and implement them in Python using a practical example.

What is Dynamic Programming?

Dynamic programming is a problem-solving technique that breaks a complex problem into smaller subproblems, solves each subproblem, and stores its result for future use. Instead of solving the same subproblem repeatedly, we save the answer and reuse it whenever needed.

DP is particularly useful when a problem has two important properties:

  • Overlapping subproblems: The same smaller problems appear multiple times during computation.
  • Optimal substructure: The solution to a larger problem can be constructed from the solutions to its smaller subproblems.

For example, consider finding the shortest route between two locations. If we already know the shortest routes between smaller sections of the journey, we can use those results to determine the overall shortest route.

Understanding Dynamic Programming with Fibonacci

The Fibonacci sequence is one of the easiest examples to understand. The sequence begins with 0 and 1. Every subsequent number is the sum of the previous two numbers.

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

For example:

  • 0 + 1 = 1
  • 1 + 1 = 2
  • 1 + 2 = 3
  • 2 + 3 = 5
  • 3 + 5 = 8

Let's say we want to calculate the Fibonacci number at position 5, counting from position 0. To calculate the number at position 5, we need the numbers at positions 4 and 3. To calculate the number at position 4, we need the numbers at positions 3 and 2.

Notice that the number at position 3 is needed more than once. This means the same calculations are repeated multiple times.

The traditional recursive approach

Here is a simple Python implementation:

def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6))

Output: 8

Although this code produces the correct result, it repeatedly calculates the same Fibonacci numbers. For example, the function calculates the number at position 3 multiple times when evaluating larger inputs.

The time complexity of this recursive approach is exponential. This means the number of calculations grows very quickly as the input increases. Dynamic programming solves this problem by storing previously calculated values.

Two approaches to Dynamic Programming

Dynamic programming is generally implemented using two approaches:

  • Memoization - Top-Down approach
  • Tabulation - Bottom-Up approach

1. Memoization (Top-Down)

Memoization uses recursion to solve a problem while storing previously calculated results. Before solving a subproblem, the program checks whether its answer is already available in memory. If it is, the stored result is returned immediately.

Python implementation:

def fibonacci(n, memo):
    if n <= 1:
        return n
    if n in memo:
        return memo[n]
    memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
    return memo[n]

memo = {}
print(fibonacci(6, memo))

Output: 8

How it works:

  • The function first checks whether the Fibonacci number has already been calculated.
  • If the value exists in memo, it returns the stored value.
  • Otherwise, it calculates the value and stores it in the dictionary.
  • Each subproblem is calculated only once.

This reduces the time complexity to O(n), with O(n) space complexity. In simple words, the program performs a number of calculations proportional to the input instead of repeating the same work many times.

2. Tabulation (Bottom-Up)

Tabulation takes a different approach. Instead of starting with the original problem and breaking it down recursively, it starts with the smallest subproblems and builds the solution step by step. It typically uses a list or table to store intermediate results.

Python implementation:

def fibonacci(n):
    if n <= 1:
        return n
    dp = [0] * (n + 1)
    dp[1] = 1
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

print(fibonacci(6))

Output: 8

Here, the program creates a list to store Fibonacci numbers. For n = 6, the list is filled as follows:

Position Fibonacci value
0 0
1 1
2 1
3 2
4 3
5 5
6 8

Each new value is calculated using the two previous values. The time complexity is O(n), and the space complexity is O(n).

Comparing the three approaches

Approach Technique Time complexity
Recursion Repeated calculations Exponential
Memoization Recursion with stored results O(n)
Tabulation Iterative table O(n)

The key difference is that both dynamic programming approaches avoid redundant calculations. Memoization is often easier to implement when a recursive solution already exists. Tabulation is useful when we can determine the order in which subproblems should be solved.

Real-world applications of Dynamic Programming

Dynamic programming is not limited to Fibonacci numbers. It is widely used in computer science, data science, and optimization. Some common applications include:

  • Shortest path algorithms: Finding efficient routes in graphs.
  • Knapsack problem: Selecting items to maximize value within a limited capacity.
  • Longest common subsequence: Comparing sequences in text processing and bioinformatics.
  • Resource allocation: Distributing limited resources to achieve an optimal outcome.

For example, in a delivery system, dynamic programming can help solve route optimization problems by storing and reusing the results of smaller route calculations.

Advantages and limitations

Advantages:

  • Reduces repeated calculations.
  • Improves the performance of recursive algorithms.
  • Helps solve complex optimization problems systematically.
  • Makes it possible to solve certain problems that would otherwise require excessive computation.

Limitations:

  • Requires additional memory to store intermediate results.
  • Not every problem has overlapping subproblems.
  • Designing a correct recurrence relation can be challenging.
  • Large DP tables may consume significant memory.

Conclusion

Dynamic programming is an important algorithmic technique that improves efficiency by solving smaller problems and storing their results. Through the Fibonacci example, we saw how a simple recursive solution can be optimized using memoization and tabulation. Both techniques reduce repeated calculations and make algorithms more efficient.

The best way to learn dynamic programming is to practice identifying overlapping subproblems, defining how smaller solutions connect, and implementing solutions using both approaches.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.