Practical No.
10
Dynamic Programming: Implement algorithms for Fibonacci series and Longest
Common Subsequence using dynamic programming.
Dynamic Programming is a method used to solve complex problems by
breaking them down into simpler subproblems. It is particularly effective when the
problem can be broken down into overlapping subproblems. DP stores the
solutions to subproblems to avoid redundant calculations and thus improves
efficiency.
Key Concepts:
1. Memoization: Storing the results of expensive function calls to avoid re-
computation.
2. Tabulation: Solving the problem by filling up a table (usually a 2D table)
iteratively.
Steps for Implementing Dynamic Programming:
1. Identify the subproblems: Break the problem into smaller overlapping
subproblems.
2. Define the DP table: Create a table (array or matrix) to store solutions to
subproblems.
3. Fill the table: Solve each subproblem and store the result.
4. Reconstruct the solution: Use the stored results to construct the final
solution.
Practical Implementation
1. Fibonacci Series using Dynamic Programming
The Fibonacci sequence is defined as:
● F(0)=0F(0) = 0F(0)=0
● F(1)=1F(1) = 1F(1)=1
● F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2)
for n>1n > 1n>1
Using Tabulation (Bottom-Up DP):
Using Memoization (Top-Down DP):
2. Longest Common Subsequence (LCS)
The Longest Common Subsequence is the longest sequence that can be
derived from two given sequences by deleting some elements (without changing
the order of the remaining elements).
The LCS problem can be solved using dynamic programming by building a 2D
table where each cell represents the length of the longest common subsequence
up to the respective characters of both strings.
LCS using Dynamic Programming (Tabulation):
Complexity:
1. Fibonacci:
○ Time Complexity: O(n)O(n)O(n) (for both tabulation and
memoization)
○ Space Complexity: O(n)O(n)O(n) (due to the table or memoization
dictionary)
2. Longest Common Subsequence (LCS):
○ Time Complexity: O(m×n)O(m \times n)O(m×n), where mmm and
nnn are the lengths of the input strings.
○ Space Complexity: O(m×n)O(m \times n)O(m×n) (for the DP table)
Practical Applications:
1. Fibonacci:
○ Used in problems involving recursion, mathematical modeling, or
optimizations.
2. Longest Common Subsequence:
○ Used in bioinformatics for DNA sequence analysis, file comparison,
and version control systems.