The Wayback Machine - https://web.archive.org/web/20240822105435/https://www.geeksforgeeks.org/overlapping-subproblems-property-in-dynamic-programming-dp-1/
Open In App

Overlapping Subproblems Property in Dynamic Programming | DP-1

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem can be solved using Dynamic programming.

  • Overlapping Subproblems 
  • Optimal Substructure

In this post, we will discuss the first property Overlapping Subproblems in detail. The second property of Dynamic programming is discussed in the next post.
 

 

Overlapping Subproblems: 

Like Divide and Conquer, Dynamic Programming combines solutions to sub-problems. Dynamic Programming is mainly used when solutions to the same subproblems are needed again and again. In dynamic programming, computed solutions to subproblems are stored in a table so that these don’t have to be recomputed. So Dynamic Programming is not useful when there are no common (overlapping) subproblems because there is no point in storing the solutions if they are not needed again. For example, Binary Search doesn’t have common subproblems. If we take the example of following a recursive program for Fibonacci Numbers, there are many subproblems that are solved again and again.

C++




#include <iostream>
using namespace std;
 
/* a simple recursive program for Fibonacci numbers */
int fib(int n)
{
    if (n <= 1)
        return n;
  
    return fib(n - 1) + fib(n - 2);
}
 
int main() {
     
    cout << fib(7);
     
    return 0;
}
 
// This code is contributed by sanjoy_62.


C




/* a simple recursive program for Fibonacci numbers */
int fib(int n)
{
    if (n <= 1)
        return n;
 
    return fib(n - 1) + fib(n - 2);
}


Java




/*package whatever //do not write package name here */
/* a simple recursive program for Fibonacci numbers */
static int fib(int n)
{
    if (n <= 1)
        return n;
 
    return fib(n - 1) + fib(n - 2);
}
 
// This code is contributed by umadevi9616


Python




#  a simple recursive program for Fibonacci numbers
def fib(n):
    if n <= 1:
        return n
 
    return fib(n - 1) + fib(n - 2)


C#




/* a simple recursive program for Fibonacci numbers */
static int fib(int n)
{
    if (n <= 1)
        return n;
 
    return fib(n - 1) + fib(n - 2);
}
 
 
// This code contributed by umadevi9616


Javascript




<script>
/*package whatever //do not write package name here */
/* a simple recursive program for Fibonacci numbers */
function fib(n)
{
    if (n <= 1)
        return n;
 
    return fib(n - 1) + fib(n - 2);
}
 
// This code is contributed by gauravrajput1
</script>


Output

13

Time Complexity: O(2N)  
Auxiliary Space: O(1)

Illustration of Recursion tree for the execution of fib(5) :                              

Recursion tree for the execution of fib(5) 

We can see that the function fib(3) is being called 2 times. If we would have stored the value of fib(3), then instead of computing it again, we could have reused the old stored value. There are following two different ways to store the values so that these values can be reused: 

  • Memoization (Top Down) 
  • Tabulation (Bottom Up)

Memoization (Top Down): 

The memoized program for a problem is similar to the recursive version with a small modification that looks into a lookup table before computing solutions. We initialize a lookup array with all initial values as NIL. Whenever we need the solution to a subproblem, we first look into the lookup table. If the precomputed value is there then we return that value, otherwise, we calculate the value and put the result in the lookup table so that it can be reused later.

Following is the memoized version for the nth Fibonacci Number. 

C++




/* C++ program for Memoized version
for nth Fibonacci number */
#include <bits/stdc++.h>
using namespace std;
#define NIL -1
#define MAX 100
 
int lookup[MAX];
 
/* Function to initialize NIL
values in lookup table */
void _initialize()
{
    int i;
    for (i = 0; i < MAX; i++)
        lookup[i] = NIL;
}
 
/* function for nth Fibonacci number */
int fib(int n)
{
    if (lookup[n] == NIL) {
        if (n <= 1)
            lookup[n] = n;
        else
            lookup[n] = fib(n - 1) + fib(n - 2);
    }
 
    return lookup[n];
}
 
// Driver code
int main()
{
    int n = 40;
    _initialize();
    cout << "Fibonacci number is " << fib(n);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




/* C program for Memoized version for nth Fibonacci number
 */
#include <stdio.h>
#define NIL -1
#define MAX 100
 
int lookup[MAX];
 
/* Function to initialize NIL values in lookup table */
void _initialize()
{
    int i;
    for (i = 0; i < MAX; i++)
        lookup[i] = NIL;
}
 
/* function for nth Fibonacci number */
int fib(int n)
{
    if (lookup[n] == NIL) {
        if (n <= 1)
            lookup[n] = n;
        else
            lookup[n] = fib(n - 1) + fib(n - 2);
    }
 
    return lookup[n];
}
 
int main()
{
    int n = 40;
    _initialize();
    printf("Fibonacci number is %d ", fib(n));
    return 0;
}


Java




/* Java program for Memoized version */
public class Fibonacci {
    final int MAX = 100;
    final int NIL = -1;
 
    int lookup[] = new int[MAX];
 
    /* Function to initialize NIL values in lookup table */
    void _initialize()
    {
        for (int i = 0; i < MAX; i++)
            lookup[i] = NIL;
    }
 
    /* function for nth Fibonacci number */
    int fib(int n)
    {
        if (lookup[n] == NIL) {
            if (n <= 1)
                lookup[n] = n;
            else
                lookup[n] = fib(n - 1) + fib(n - 2);
        }
        return lookup[n];
    }
 
    public static void main(String[] args)
    {
        Fibonacci f = new Fibonacci();
        int n = 40;
        f._initialize();
        System.out.println("Fibonacci number is"
                           + " " + f.fib(n));
    }
}
// This Code is Contributed by Saket Kumar


Python




# a program for Memoized version of nth Fibonacci number
 
# function to calculate nth Fibonacci number
 
 
def fib(n, lookup):
 
    # base case
    if n <= 1:
        lookup[n] = n
 
    # if the value is not calculated previously then calculate it
    if lookup[n] is None:
        lookup[n] = fib(n-1, lookup) + fib(n-2, lookup)
 
    # return the value corresponding to that value of n
    return lookup[n]
# end of function
 
# Driver program to test the above function
 
 
def main():
    n = 34
    # Declaration of lookup table
    # Handles till n = 100
    lookup = [None] * 101
    print "Fibonacci Number is ", fib(n, lookup)
 
 
if __name__ == "__main__":
    main()
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// C# program for Memoized versionof nth Fibonacci number
using System;
 
class GFG {
 
    static int MAX = 100;
    static int NIL = -1;
    static int[] lookup = new int[MAX];
 
    /* Function to initialize NIL
    values in lookup table */
    static void initialize()
    {
        for (int i = 0; i < MAX; i++)
            lookup[i] = NIL;
    }
 
    /* function for nth Fibonacci number */
    static int fib(int n)
    {
        if (lookup[n] == NIL) {
            if (n <= 1)
                lookup[n] = n;
            else
                lookup[n] = fib(n - 1) + fib(n - 2);
        }
        return lookup[n];
    }
 
    // Driver code
    public static void Main()
    {
 
        int n = 40;
        initialize();
        Console.Write("Fibonacci number is"
                      + " " + fib(n));
    }
}
 
// This Code is Contributed by Sam007


Javascript




<script>
 
let  MAX = 100;
let NIL = -1;
 
let lookup = new Array(MAX);
 
function  _initialize()
{
    for (let i = 0; i < MAX; i++)
        lookup[i] = NIL;
}
 
function fib(n)
{
    if (lookup[n] == NIL)
    {
      if (n <= 1)
          lookup[n] = n;
      else
          lookup[n] = fib(n-1) + fib(n-2);
    }
    return lookup[n];
}
 
 
let n = 40;
_initialize();
document.write("Fibonacci number is" + " " + fib(n)+"<br>");
 
// This code is contributed by avanitrachhadiya2155
</script>


Output

Fibonacci number is 102334155

Time Complexity: O(N). This is because the algorithm computes each Fibonacci number only once and stores the result in an array for future use. Subsequent calls to the function with the same input value of n will retrieve the stored value from the lookup table, avoiding the need to recompute it. Therefore, the time complexity is linear, and the algorithm is very efficient for large values of n.

Space Complexity: O(N) as lookup table has been created.

Tabulation (Bottom Up): 

The tabulated program for a given problem builds a table in a bottom-up fashion and returns the last entry from the table. For example, for the same Fibonacci number, we first calculate fib(0) then fib(1) then fib(2) then fib(3), and so on. So literally, we are building the solutions to subproblems bottom-up. 

Following is the tabulated version for the nth Fibonacci Number.

C




/* C program for Tabulated version */
#include <stdio.h>
int fib(int n)
{
    int f[n + 1];
    int i;
    f[0] = 0;
    f[1] = 1;
    for (i = 2; i <= n; i++)
        f[i] = f[i - 1] + f[i - 2];
 
    return f[n];
}
 
int main()
{
    int n = 9;
    printf("Fibonacci number is %d ", fib(n));
    return 0;
}


Java




/* Java program for Tabulated version */
public class Fibonacci {
    int fib(int n)
    {
        int f[] = new int[n + 1];
        f[0] = 0;
        f[1] = 1;
        for (int i = 2; i <= n; i++)
            f[i] = f[i - 1] + f[i - 2];
        return f[n];
    }
 
    public static void main(String[] args)
    {
        Fibonacci f = new Fibonacci();
        int n = 9;
        System.out.println("Fibonacci number is"
                           + " " + f.fib(n));
    }
}
// This Code is Contributed by Saket Kumar


Python




# Python program Tabulated (bottom up) version
def fib(n):
 
    # array declaration
    f = [0] * (n + 1)
 
    # base case assignment
    f[1] = 1
 
    # calculating the fibonacci and storing the values
    for i in xrange(2, n + 1):
        f[i] = f[i - 1] + f[i - 2]
    return f[n]
 
# Driver program to test the above function
 
 
def main():
    n = 9
    print "Fibonacci number is ", fib(n)
 
 
if __name__ == "__main__":
    main()
 
# This code is contributed by Nikhil Kumar Singh (nickzuck_007)


C#




// C# program for Tabulated version
using System;
 
class GFG {
    static int fib(int n)
    {
        int[] f = new int[n + 1];
        f[0] = 0;
        f[1] = 1;
        for (int i = 2; i <= n; i++)
            f[i] = f[i - 1] + f[i - 2];
        return f[n];
    }
 
    public static void Main()
    {
 
        int n = 9;
        Console.Write("Fibonacci number is"
                      + " " + fib(n));
    }
}
 
// This Code is Contributed by Sam007


Javascript




<script>
 
// Javascript program for Tabulated version
function fib(n)
{
    var f = new Array(n + 1);
    var i;
     
    f[0] = 0;
    f[1] = 1;
    for(i = 2; i <= n; i++)
        f[i] = f[i - 1] + f[i - 2];
     
    return f[n];
}
 
// Driver code
var n = 9;
document.write("Fibonacci number is  " + fib(n));
 
// This code is contributed by akshitsaxenaa09
 
</script>


PHP




<?php
// PHP program for Tabulated version
 
function fib($n)
{
    $f[$n + 1]=0;
    $i;
    $f[0] = 0;
    $f[1] = 1;
    for ($i = 2; $i <= $n; $i++)
        $f[$i] = $f[$i - 1] +
                 $f[$i - 2];
     
    return $f[$n];
}
 
// Driver Code
$n = 9;
echo("Fibonacci number is ");
echo(fib($n));
 
// This code is contributed by nitin mittal.
?>


C++




/* C++ program for Tabulated version */
 
#include <iostream>
using namespace std;
 
int fib(int n)
{
    int f[n + 1];
    int i;
    f[0] = 0;
    f[1] = 1;
    for (i = 2; i <= n; i++)
        f[i] = f[i - 1] + f[i - 2];
 
    return f[n];
}
 
int main()
{
    int n = 9;
    printf("Fibonacci number is %d ", fib(n));
    return 0;
}


Output

Fibonacci number is 34 

Time Complexity: O(N)
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Optimal Substructure Property in Dynamic Programming | DP-2
As we discussed in Set 1, the following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property in Set 1. Let us discuss the Optimal Substructure property here. In Dynamic pro
9 min read
Introduction to Dynamic Programming on Trees
Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied on trees to solve some specific problems.Pre-requisite: DFSGiven a tree with N nodes and N-1 edges
10 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is d
12 min read
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
Given a N-ary tree with a value associated with each node, the task is to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.Examples:
9 min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been discussed here using Manacher’s algorithm. However
8 min read
Longest path in a directed Acyclic graph | Dynamic Programming
Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1-&gt;3-&gt;2-&gt;4 Input: N = 5, M = 8 Output: 3 Simple Approach: A naive approach is to calculate the len
8 min read
Count of numbers from range [L, R] whose sum of digits is Y using Dynamic Programming
Pre-requisites: Recursion, Dynamic Programming, Digit DP Given an integer Y and a range [L, R], the task is to find the count of all numbers from the given range whose sum of digits is equal to Y.Examples: Input: L = 0, R = 11, Y = 2 Output: 2 2 -&gt; 2 11 -&gt; 1 + 1 = 2Input: L = 500, R = 1000, Y = 6 Output: 3 Constraints: 0 &lt;= L &lt;= R &lt;=
10 min read
Minimum time required to rot all oranges | Dynamic Programming
Given a matrix of dimension m * n where each cell in the matrix can have values 0, 1, or 2 which has the following meaning: 0: Empty cell 1: Cells have fresh oranges 2: Cells have rotten oranges So the task is to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh or
15 min read
Reliability Design Problem in Dynamic Programming
The reliability design problem is the designing of a system composed of several devices connected in series or parallel. Reliability means the probability to get the success of the device. Let's say, we have to set up a system consisting of D1, D2, D3, ............, and Dn devices, each device has some costs C1, C2, C3, ........, Cn. Each device ha
6 min read
Convert N to M with given operations using dynamic programming
Given two integers N and M and the task is to convert N to M with the following operations: Multiply N by 2 i.e. N = N * 2.Subtract 1 from N i.e. N = N - 1. Examples: Input: N = 4, M = 6 Output: 2 Perform operation 2: N = N - 1 = 4 - 1 = 3 Perform operation 1: N = N * 2 = 3 * 2 = 6 Input: N = 10, M = 1 Output: 9 Approach: Create an array dp[] of si
7 min read
Longest subsequence with a given OR value : Dynamic Programming Approach
Given an array arr[], the task is to find the longest subsequence with a given OR value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 2, 3} is the required subsequence 3 | 2 | 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Approach: A simple solution is to generate all the possible sub-sequ
6 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Ackermann's function using Dynamic programming
Given two non-zero integers M and N, the problem is to compute the result of the Ackermann function based on some particular equations. Ackermann function is defined as: Examples: Input: M = 2, N = 2Output: 7 Input: M = 2, N = 7Output: 6141004759 The approach for Ackermann function described in this article, takes a very huge amount of time to comp
13 min read
Count ways to select N pairs of candies of distinct colors (Dynamic Programming + Bitmasking)
Given an integer N representing the number of red and blue candies and a matrix mat[][] of size N * N, where mat[i][j] = 1 represents the existence of a pair between ith red candy and jth blue candy, the task is to find the count of ways to select N pairs of candies such that each pair contains distinct candies of different colors. Examples: Input:
13 min read
Hamiltonian Path ( Using Dynamic Programming )
Given an adjacency matrix adj[][] of an undirected graph consisting of N vertices, the task is to find whether the graph contains a Hamiltonian Path or not. If found to be true, then print "Yes". Otherwise, print "No". A Hamiltonian path is defined as the path in a directed or undirected graph which visits each and every vertex of the graph exactly
10 min read
Minimum moves to make M and N equal by repeated addition of divisors except 1 using Dynamic Programming
Given two integers N and M, the task is to calculate the minimum number of moves to change N to M, where In one move it is allowed to add any divisor of the current value of N to N itself except 1. Print "-1" if it is not possible. Example: Input: N = 4, M = 24Output: 5Explanation: The given value of N can be converted into M using the following st
8 min read
Dynamic Programming meaning in DSA
Dynamic Programming is defined as an algorithmic technique that is used to solve problems by breaking them into smaller subproblems and avoiding repeated calculation of overlapping subproblems and using the property that the solution of the problem depends on the optimal solution of the subproblems Properties of Dynamic Programming:Optimal Substruc
2 min read
Knuth's Optimization in Dynamic Programming
Knuth's optimization is a very powerful tool in dynamic programming, that can be used to reduce the time complexity of the solutions primarily from O(N3) to O(N2). Normally, it is used for problems that can be solved using range DP, assuming certain conditions are satisfied. In this article, we will first explore the optimization itself, and then s
15+ min read
Divide and Conquer Optimization in Dynamic Programming
Dynamic programming (DP) is arguably the most important tool in a competitive programmer's repertoire. There are several optimizations in DP that reduce the time complexity of standard DP procedures by a linear factor or more, such as Knuth's optimization, Divide and Conquer optimization, the Convex Hull Trick, etc. They are, of paramount importanc
15+ min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm
Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms: Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.Divide and conquer algorithm: Breaks down a probl
4 min read
Expected number of moves to reach the end of a board | Dynamic programming
Given a linear board of length N numbered from 1 to N, the task is to find the expected number of moves required to reach the Nth cell of the board, if we start at cell numbered 1 and at each step we roll a cubical dice to decide the next move. Also, we cannot go outside the bounds of the board. Note that the expected number of moves can be fractio
11 min read
Double Knapsack | Dynamic Programming
Given an array 'arr' containing the weight of 'N' distinct items, and two knapsacks that can withstand 'W1' and 'W2' weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e an item should be put in one of the bags as a whole.Examples: Input
15+ min read
Number of Unique BST with a given key | Dynamic Programming
Given N, The task is to find the total number of unique BSTs that can be made using values from 1 to N. Examples: Input: N = 3 Output: 5Explanation: For N = 3, preorder traversal of Unique BSTs are:1 2 31 3 22 1 33 1 23 2 1 Input: N = 4 Output: 14 Recommended PracticeUnique BST'sTry It! Approach: The solution is based on Dynamic Programming. For al
6 min read
Optimal Strategy for the Divisor game using Dynamic Programming
Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game
9 min read
Longest Palindromic Substring using Dynamic Programming
Given a string, find the longest substring which is a palindrome. Examples: Input: Given string :"forgeeksskeegfor", Output: "geeksskeeg".Input: Given string :"Geeks", Output: "ee". Recommended PracticeLongest Palindrome in a StringTry It!BRUTE APPROACH: (TABULATION METHOD)Intuition: We create a 2-D array to fill the array with appropriate steps.We
15+ min read
Largest Independent Set Problem using Dynamic Programming
Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset. For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5. Recommended PracticeLargest Independen
15+ min read
Travelling Salesman Problem using Dynamic Programming
Travelling Salesman Problem (TSP): Given a set of cities and the distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point. Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that
13 min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for tre
15+ min read
three90RightbarBannerImg