We shall continue with the example of finding the nth Fibonacci number in order to understand the DP methods available. We have the following two methods in DP technique. We can use any one of these techniques to solve a problem in optimised manner.
Top Down Approach is the method where we solve a bigger problem by recursively finding the solution to smaller sub-problems.
Whenever we solve a smaller subproblem, we remember (cache) its result so that we don’t solve it repeatedly if it’s called many times. Instead of solving repeatedly, we can just return the cached result.
This method of remembering the solutions of already solved subproblems is called Memoization.
Without Memoization
Think of a recursive approach to solving the problem. This part is simple. We already know Fib(n) = Fib(n - 1) + Fib(n - 2)
.
Write a recursive code for the approach you just thought of.
/**
* Pseudo code for finding Fib(n) without memoization
* @Parameters: n : nth Fibonacci term needed
*
*/
int Fib(int n) {
if (n <= 1) return n; //Fib(0)=0; Fib(1)=1
return Fib(n - 1) + Fib(n - 2);
}
The time complexity of the above approach based on careful analysis on the property of recursion shows that it is essentially exponential in terms of n because some terms are evaluated again and again.
With Memoization
Fib(n)
is called again, you do not recompute the whole thing.
memo
then.
/**
* Pseudo code for finding Fib(n) with memoization
* @Parameters: n : nth Fibonacci term needed
*
*/
int memo[100] = {0};
int Fib(int n) {
if (n <= 1) return n;
// If we have processed this function before,
// return the result from the last time.
if (memo[n] != 0) return memo[n];
// Otherwise calculate the result and remember it.
memo[n] = Fib(n - 1) + Fib(n - 2);
return memo[n];
}
O(n)
.
O(n)
. So, overall space complexity is O(n) + O(n) = 2 O(n) = O(n)
.
Lets look at Fib(n)
.
When Fib(n - 1)
is called, it makes a call to Fib(n - 2)
. So when the call comes back to the original call from Fib(n)
, Fib(n-2)
would already be calculated. Hence the call to Fib(n - 2)
will be O(1).
Hence,
T(n) = T(n - 1) + c where c is a constant.
= T(n - 2) + 2c
= T(n - 3) + 3c
= T(n - k) + kc
= T(0) + n * c = 1 + n * c = O(n)
Thanks to Dynamic Programming, we have successfully reduced a exponential problem to a linear problem.
/* C Program to find Nth Fibonacci Number using Memoization */
#include<stdio.h>
int Fibonacci_Series(int);
int memo[100] = {0};
int main()
{
int N, FibN;
printf("\n Enter the Number to find Nth Fibonacci Number : ");
scanf("%d", &N);
FibN = Fibonacci_Series(N);
printf("\n Fibonacci Number = %d", FibN);
return 0;
}
int Fibonacci_Series(int N)
{
if ( N == 0 )
return 0;
else if ( N == 1 )
return 1;
if (memo[n] != 0) return memo[n];
else{
memo[n]=Fibonacci_Series(N - 1) + Fibonacci_Series(N - 2)
return memo[n];
}
}
/* C++ Program to find Nth Fibonacci Number using Memoization */
#include <bits/stdc++.h>
using namespace std;
#define NIL -1
int memo[100];
/* Function to initialize NIL values in memo */
void initializeMemo()
{
int i;
for (i = 0; i < 100; i++)
memo[i] = NIL;
}
int fib(int n)
{
if (memo[n] == NIL)
{
if (n <= 1)
memo[n] = n;
else
memo[n] = fib(n - 1) + fib(n - 2);
}
return memo[n];
}
// Main Driver code
int main ()
{
int n = 10;
initializeMemo();
cout << "Fibonacci number : " << fib(n);
return 0;
}
/* Java Program to find Nth Fibonacci Number using Memoization */
public class Fibonacci
{
final int NIL = -1;
int memo[] = new int[100];
/* Function to initialize NIL values in memo */
void initializeMemo()
{
for (int i = 0; i < 100; i++)
memo[i] = NIL;
}
int fib(int n)
{
if (memo[n] == NIL)
{
if (n <= 1)
memo[n] = n;
else
memo[n] = fib(n-1) + fib(n-2);
}
return memo[n];
}
//Main Driver class
public static void main(String[] args)
{
Fibonacci fibonacci = new Fibonacci();
int n = 10;
fibonacci.initializeMemo();
System.out.println("Fibonacci number : " + fibonacci.fib(n));
}
}
# Python Program to find Nth Fibonacci Number using Memoization
def fib(n, memo):
# Base case
if n == 0 or n == 1 :
memo[n] = n
# If memo[n] is not evaluated before then calculate it
if memo[n] is None:
memo[n] = fib(n-1 , memo) + fib(n-2 , memo)
# return the value corresponding value of n
return memo[n]
# Driver program
def main():
n = 10
# Declaration of memo
memo = [None]*(101)
# Calculate and display result
print("Fibonacci Number is " + str(fib(n, lookup)))
if __name__=="__main__":
main()
As the name indicates, bottom up is the opposite of the top-down approach which avoids recursion.
Here, we solve the problem “bottom-up” way i.e. by solving all the related subproblems first. This is typically done by populating into an n-dimensional table.
Depending on the results in the table, the solution to the original problem is then computed. This approach is therefore called as “Tabulation”.
Fib(n) = Fib(n - 1) + Fib(n - 2)
.
/**
* Pseudo code for finding Fib(n) using tabulation
* @Parameters: n : nth Fibonacci term needed
* local variable dp[] table built to store results of smaller subproblems
*/
int Fib(int n) {
if (n==0) return 0;
int dp[] = new int[n+1];
//define base cases
dp[0] = 0;
dp[1] = 1;
//Iteratively compute the results and store
for(int i=2; i<=n; i++)
dp[i] = dp[i-1] + dp[i-2];
//return the value corresponding to nth term
return dp[n];
}
O(n)
.
O(N)
to O(1)
by just using 2 variables. This is left as an assignment to the reader.
Fib(n)
.
/* C Program to find Nth Fibonacci Number using Tabulation */
#include<stdio.h>
int fib(int n)
{
int dp[n+1];
int i;
//base cases
dp[0] = 0; dp[1] = 1;
//calculating and storing the values
for (i = 2; i <= n; i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n];
}
int main ()
{
int n = 10;
printf("Fibonacci number : %d ", fib(n));
return 0;
}
/* C++ Program to find Nth Fibonacci Number using Tabulation */
#include <bits/stdc++.h>
using namespace std;
int fib(int n)
{
int dp[n+1];
int i;
//base cases
dp[0] = 0; dp[1] = 1;
//calculating and storing the values
for (i = 2; i <= n; i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n];
}
// Main Driver code
int main ()
{
int n = 10;
cout << "Fibonacci number : " << fib(n);
return 0;
}
/* Java Program to find Nth Fibonacci Number using Tabulation */
public class Fibonacci
{
int fib(int n){
int dp[] = new int[n+1];
//base cases
dp[0] = 0;
dp[1] = 1;
//calculating and storing the values
for (int i = 2; i <= n; i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n];
}
public static void main(String[] args)
{
Fibonacci fibonacci = new Fibonacci();
int n = 10;
System.out.println("Fibonacci number : " + fibonacci.fib(n));
}
}
# Python Program to find Nth Fibonacci Number using Tabulation
def fib(n):
# dp array declaration
dp = [0]*(n+1)
# base case
dp[1] = 1
# calculating and storing the values
for i in xrange(2 , n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
# Driver program
def main():
n = 10
print("Fibonacci number : " + str(fib(n)))
if __name__=="__main__":
main()
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Longest Common Subsequence | 200 |
|
42:05 | |
Longest Palindromic Subsequence | 200 |
|
41:12 | |
Edit Distance | 300 |
|
47:01 | |
Repeating Sub-Sequence | 300 |
|
64:12 | |
Distinct Subsequences | 325 |
|
65:51 | |
Scramble String | 500 |
|
72:55 | |
Regular Expression Match | 500 |
|
79:42 | |
Regular Expression II | 500 |
|
70:41 | |
Interleaving Strings | 500 |
|
62:16 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Length of Longest Subsequence | 200 |
|
65:01 | |
Smallest sequence with given Primes | 200 |
|
67:33 | |
Largest area of rectangle with permutations | 200 |
|
76:53 | |
Tiling With Dominoes | 200 |
|
63:46 | |
Paint House! | 200 |
|
41:36 | |
Ways to Decode | 225 |
|
70:08 | |
Stairs | 225 |
|
15:14 | |
Longest Increasing Subsequence | 300 |
|
30:39 | |
Intersecting Chords in a Circle | 300 |
|
70:18 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Tushar's Birthday Bombs | 200 |
|
80:41 | |
Jump Game Array | 225 |
|
41:16 | |
Min Jumps Array | 300 |
|
71:56 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Longest Arithmetic Progression | 200 |
|
75:50 | |
N digit numbers with digit sum S | 200 |
|
73:15 | |
Shortest common superstring | 200 |
|
58:52 | |
Ways to color a 3xN Board | 200 |
|
65:27 | |
Kth Manhattan Distance Neighbourhood | 200 |
|
64:27 | |
Best Time to Buy and Sell Stock atmost B times | 200 |
|
63:42 | |
Coins in a Line | 300 |
|
63:59 | |
Evaluate Expression To True | 350 |
|
72:21 | |
Egg Drop Problem! | 450 |
|
56:20 | |
Best Time to Buy and Sell Stocks III | 700 |
|
64:45 | |
Longest valid Parentheses | 700 |
|
62:33 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Max edge queries! | 200 |
|
57:33 | |
Max Sum Path in Binary Tree | 400 |
|
55:23 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Kingdom War | 200 |
|
60:45 | |
Maximum Path in Triangle | 200 |
|
33:39 | |
Maximum Size Square Sub-matrix | 200 |
|
44:49 | |
Increasing Path in Matrix | 200 |
|
47:20 | |
Minimum Difference Subsets! | 200 |
|
52:00 | |
Subset Sum Problem! | 200 |
|
45:46 | |
Unique Paths in a Grid | 300 |
|
34:08 | |
Dungeon Princess | 300 |
|
71:54 | |
Min Sum Path in Matrix | 300 |
|
30:33 | |
Min Sum Path in Triangle | 300 |
|
43:26 | |
Max Rectangle in Binary Matrix | 350 |
|
79:20 | |
Rod Cutting | 350 |
|
76:16 | |
Queen Attack | 350 |
|
61:43 | |
Dice Throw | 400 |
|
49:47 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Sub Matrices with sum Zero | 200 |
|
75:37 | |
Coin Sum Infinite | 225 |
|
65:14 | |
Max Product Subarray | 300 |
|
65:25 | |
Best Time to Buy and Sell Stocks I | 300 |
|
28:13 | |
Arrange II | 350 |
|
73:42 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Chain of Pairs | 200 |
|
44:13 | |
Max Sum Without Adjacent Elements | 225 |
|
58:16 | |
Merge elements | 300 |
|
64:14 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Flip Array | 200 |
|
81:31 | |
Tushar's Birthday Party | 200 |
|
72:55 | |
0-1 Knapsack | 200 |
|
49:10 | |
Equal Average Partition | 350 |
|
75:11 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Potions | 200 |
|
52:48 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Best Time to Buy and Sell Stocks II | 225 |
|
40:18 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Word Break II | 350 |
|
68:51 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Unique Binary Search Trees II | 400 |
|
36:30 | |
Count Permutations of BST | 400 |
|
60:02 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Palindrome Partitioning II | 400 |
|
62:59 | |
Word Break | 400 |
|
68:17 |