The Wayback Machine - https://web.archive.org/web/20240819102611/https://www.geeksforgeeks.org/dynamic-programming-vs-divide-and-conquer/
Open In App

Dynamic Programming vs Divide-and-Conquer

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

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 Problem
When I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is different from divide-and-conquer (DC) approach. When it gets to comparing those two paradigms usually Fibonacci function comes to the rescue as great example. But when we’re trying to solve the same problem using both DP and DC approaches to explain each of them, it feels for me like we may lose valuable detail that might help to catch the difference faster. And these detail tells us that each technique serves best for different types of problems.
I’m still in the process of understanding DP and DC difference and I can’t say that I’ve fully grasped the concepts so far. But I hope this article will shed some extra light and help you to do another step of learning such valuable algorithm paradigms as dynamic programming and divide-and-conquer.
Dynamic Programming and Divide-and-Conquer Similarities
As I see it for now I can say that dynamic programming is an extension of divide and conquer paradigm.
I would not treat them as something completely different. Because they both work by recursively breaking down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem.
So why do we still have different paradigm names then and why I called dynamic programming an extension. It is because dynamic programming approach may be applied to the problem only if the problem has certain restrictions or prerequisites. And after that dynamic programming extends divide and conquer approach with memoization or tabulation technique.
Let’s go step by stepâ€Ķ
Dynamic Programming Prerequisites/Restrictions
As we’ve just discovered there are two key attributes that divide and conquer problem must have in order for dynamic programming to be applicable:

Once these two conditions are met we can say that this divide and conquer problem may be solved using dynamic programming approach.
Dynamic Programming Extension for Divide and Conquer
Dynamic programming approach extends divide and conquer approach with two techniques (memoization and tabulation) that both have a purpose of storing and re-using sub-problems solutions that may drastically improve performance. For example naive recursive implementation of Fibonacci function has time complexity of O(2^n) where DP solution doing the same with only O(n) time.
Memoization (top-down cache filling) refers to the technique of caching and reusing previously computed results. The memoized fib function would thus look like this:
 

memFib(n) {
    if (mem[n] is undefined)
        if (n < 2) result = n
        else result = memFib(n-2) + memFib(n-1)
        mem[n] = result
    return mem[n]
}

Tabulation (bottom-up cache filling) is similar but focuses on filling the entries of the cache. Computing the values in the cache is easiest done iteratively. The tabulation version of fib would look like this:
 

tabFib(n) {
    mem[0] = 0
    mem[1] = 1
    for i = 2...n
        mem[i] = mem[i-2] + mem[i-1]
    return mem[n]
}

You may read more about memoization and tabulation comparison here.
The main idea you should grasp here is that because our divide and conquer problem has overlapping sub-problems the caching of sub-problem solutions becomes possible and thus memoization/tabulation step up onto the scene.
So What the Difference Between DP and DC After All
Since we’re now familiar with DP prerequisites and its methodologies we’re ready to put all that was mentioned above into one picture.
Dynamic programming and divide and conquer paradigms dependency

Let’s go and try to solve some problems using DP and DC approaches to make this illustration more clear.
Divide and Conquer Example: Binary Search
Binary search algorithm, also known as half-interval search, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.
Example
Here is a visualization of the binary search algorithm where 4 is the target value.

Binary search algorithm logic

Let’s draw the same logic but in form of decision tree.
Binary search algorithm decision tree

You may clearly see here a divide and conquer principle of solving the problem. We’re iteratively breaking the original array into sub-arrays and trying to find required element in there.
Can we apply dynamic programming to it? No. It is because there are no overlapping sub-problems. Every time we split the array into completely independent parts. And according to divide and conquer prerequisites/restrictions the sub-problems must be overlapped somehow.
Normally every time you draw a decision tree and it is actually a tree (and not a decision graph) it would mean that you don’t have overlapping sub-problems and this is not dynamic programming problem.
The Code
Here you may find complete source code of binary search function with test cases and explanations.
 

function binarySearch(sortedArray, seekElement) {
  let startIndex = 0;
  let endIndex = sortedArray.length - 1;
  while (startIndex <= endIndex) {
    const middleIndex = startIndex + Math.floor((endIndex - startIndex) / 2);
    // If we've found the element just return its position.
    if (sortedArray[middleIndex] === seekElement)) {
      return middleIndex;
    }
    // Decide which half to choose: left or right one.
    if (sortedArray[middleIndex] < seekElement)) {
      // Go to the right half of the array.
      startIndex = middleIndex + 1;
    } else {
      // Go to the left half of the array.
      endIndex = middleIndex - 1;
    }
  }
  return -1;
}

Dynamic Programming Example: Minimum Edit Distance
Normally when it comes to dynamic programming examples the Fibonacci number algorithm is being taken by default. But let’s take a little bit more complex algorithm to have some kind of variety that should help us to grasp the concept.
Minimum Edit Distance (or Levenshtein Distance) is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other.
Example
For example, the Levenshtein distance between “kitten” and “sitting” is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits:

Applications
This has a wide range of applications, for instance, spell checkers, correction systems for optical character recognition, fuzzy string searching, and software to assist natural language translation based on translation memory.
Mathematical Definition
Mathematically, the Levenshtein distance between two strings a, b (of length |a| and |b| respectively) is given by function lev(|a|, |b|) where

Note that the first element in the minimum corresponds to deletion (from a to b), the second to insertion and the third to match or mismatch, depending on whether the respective symbols are the same.
Explanation
Ok, let’s try to figure out what that formula is talking about. Let’s take a simple example of finding minimum edit distance between strings ME and MY. Intuitively you already know that minimum edit distance here is 1 operation and this operation is “replace E with Y”. But let’s try to formalize it in a form of the algorithm in order to be able to do more complex examples like transforming Saturday into Sunday.
To apply the formula to ME>MY transformation we need to know minimum edit distances of ME>M, M>MY and M>M transformations in prior. Then we will need to pick the minimum one and add +1 operation to transform last letters E?Y.
So we can already see here a recursive nature of the solution: minimum edit distance of ME>MY transformation is being calculated based on three previously possible transformations. Thus we may say that this is divide and conquer algorithm.
To explain this further let’s draw the following matrix.

Simple example of finding minimum edit distance between ME and MY strings

Cell (0, 1) contains red number 1. It means that we need 1 operation to transform M to empty string: delete M. This is why this number is red.
Cell (0, 2) contains red number 2. It means that we need 2 operations to transform ME to empty string: delete E, delete M.
Cell (1, 0) contains green number 1. It means that we need 1 operation to transform empty string to M: insert M. This is why this number is green.
Cell (2, 0) contains green number 2. It means that we need 2 operations to transform empty string to MY: insert Y, insert M.
Cell (1, 1) contains number 0. It means that it costs nothing to transform M to M.
Cell (1, 2) contains red number 1. It means that we need 1 operation to transform ME to M: delete E.
And so onâ€Ķ
This looks easy for such small matrix as ours (it is only 3×3). But how we could calculate all those numbers for bigger matrices (let’s say 9×7 one, for Saturday>Sunday transformation)?
The good news is that according to the formula you only need three adjacent cells (i-1, j), (i-1, j-1), and (i, j-1) to calculate the number for current cell (i, j) . All we need to do is to find the minimum of those three cells and then add +1 in case if we have different letters in i-s row and j-s column
So once again you may clearly see the recursive nature of the problem.

Recursive nature of minimum edit distance problem

Ok we’ve just found out that we’re dealing with divide and conquer problem here. But can we apply dynamic programming approach to it? Does this problem satisfies our overlapping sub-problems and optimal substructure restrictions? Yes. Let’s see it from decision graph.

Decision graph for minimum edit distance with overlapping sub-problems

First of all this is not a decision tree. It is a decision graph. You may see a number of overlapping subproblems on the picture that are marked with red. Also there is no way to reduce the number of operations and make it less then a minimum of those three adjacent cells from the formula.
Also you may notice that each cell number in the matrix is being calculated based on previous ones. Thus the tabulation technique (filling the cache in bottom-up direction) is being applied here. You’ll see it in code example below.
Applying these principles further we may solve more complicated cases like with Saturday > Sunday transformation.

Minimum edit distance to convert Saturday to Sunday

The Code
Here you may find complete source code of minimum edit distance function with test cases and explanations.
 

function levenshteinDistance(a, b) {
  const distanceMatrix = Array(b.length + 1)
    .fill(null)
    .map(
      () => Array(a.length + 1).fill(null)
    );

  for (let i = 0; i <= a.length; i += 1) {
    distanceMatrix[0][i] = i;
  }

  for (let j = 0; j <= b.length; j += 1) {
    distanceMatrix[j][0] = j;
  }
  
  for (let j = 1; j <= b.length; j += 1) {
    for (let i = 1; i <= a.length; i += 1) {
      const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
      
      distanceMatrix[j][i] = Math.min(
        distanceMatrix[j][i - 1] + 1, // deletion
        distanceMatrix[j - 1][i] + 1, // insertion
        distanceMatrix[j - 1][i - 1] + indicator, // substitution
      );
    }
  }

  return distanceMatrix[b.length][a.length];
}

Conclusion
In this article we have compared two algorithmic approaches such as dynamic programming and divide-and-conquer. We’ve found out that dynamic programming is based on divide and conquer principle and may be applied only if the problem has overlapping sub-problems and optimal substructure (like in Levenshtein distance case). Dynamic programming then is using memoization or tabulation technique to store solutions of overlapping sub-problems for later usage.
I hope this article hasn’t brought you more confusion but rather shed some light on these two important algorithmic concepts! ðŸ™‚
You may find more examples of divide and conquer and dynamic programming problems with explanations, comments and test cases in JavaScript Algorithms and Data Structures repository.
Happy coding!

Dynamic programming and divide-and-conquer are two commonly used algorithms design techniques that can be used to solve a variety of problems.

  1. Dynamic Programming is a technique used for solving problems by breaking them down into smaller overlapping subproblems and storing the results of these subproblems to avoid redundant computation. It is used when the problem exhibits optimal substructure, meaning that the optimal solution can be constructed from optimal solutions of subproblems. It is well-suited for problems that have an inherent sequence, such as making a sequence of decisions. Some common examples of problems solved using dynamic programming include finding the longest common subsequence, the shortest path in a graph, and the Fibonacci sequence.
  2. Divide-and-Conquer is a technique used for solving problems by breaking them down into smaller subproblems that can be solved independently and then combining these solutions to obtain the solution to the original problem. It is used when the problem can be divided into smaller subproblems that are similar to the original problem, and the solution to the subproblems can be combined to form a solution to the original problem. Some common examples of problems solved using divide-and-conquer include the quick sort algorithm, binary search, and the merge sort algorithm.

In summary, dynamic programming is used when the problem has an optimal substructure and can be solved using a bottom-up approach, while divide-and-conquer is used when the problem can be divided into smaller subproblems that are similar to the original problem and solved using a top-down approach.



Previous Article
Next Article

Similar Reads

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
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
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm
Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. A linear time complexity is discussed in the previous post. This problem can also be a very good example for divide and conquer algorithms. Following is divide and conquer algorithm.1) Find the middle elemen
15+ min read
Advantages and Disadvantages of Divide and Conquer Algorithms
Divide and Conquer is an algorithmic paradigm in which the problem is solved using the Divide, Conquer, and Combine strategy. A typical divide-and-conquer algorithm solves a problem using the following three steps: Divide: This involves dividing the problem into smaller sub-problems.Conquer: Solve sub-problems by calling recursively until solved.Co
2 min read
Closest Pair of Points using Divide and Conquer algorithm
We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for dist
15+ min read
Advanced master theorem for divide and conquer recurrences
The Master Theorem is a tool used to solve recurrence relations that arise in the analysis of divide-and-conquer algorithms. The Master Theorem provides a systematic way of solving recurrence relations of the form: T(n) = aT(n/b) + f(n) where a, b, and f(n) are positive functions and n is the size of the problem. The Master Theorem provides conditi
5 min read
Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach )
Giving k sorted arrays, each of size N, the task is to merge them into a single sorted array. Examples: Input: arr[][] = {{5, 7, 15, 18}, {1, 8, 9, 17}, {1, 4, 7, 7}} Output: {1, 1, 4, 5, 7, 7, 7, 8, 9, 15, 17, 18} Input: arr[][] = {{3, 2, 1} {6, 5, 4}} Output: {1, 2, 3, 4, 5, 6} Prerequisite: Merge SortSimple Approach: A simple solution is to appe
15+ min read
Merge K sorted arrays of different sizes | ( Divide and Conquer Approach )
Given k sorted arrays of different length, merge them into a single array such that the merged array is also sorted.Examples: Input : {{3, 13}, {8, 10, 11} {9, 15}} Output : {3, 8, 9, 10, 11, 13, 15} Input : {{1, 5}, {2, 3, 4}} Output : {1, 2, 3, 4, 5} Let S be the total number of elements in all the arrays.Simple Approach: A simple approach is to
8 min read
Sum of maximum of all subarrays | Divide and Conquer
Given an array arr[] of length N, the task is to find the sum of the maximum elements of every possible sub-array of the array.Examples: Input : arr[] = {1, 3, 1, 7} Output : 42 Max of all sub-arrays: {1} - 1 {1, 3} - 3 {1, 3, 1} - 3 {1, 3, 1, 7} - 7 {3} - 3 {3, 1} - 3 {3, 1, 7} - 7 {1} - 1 {1, 7} - 7 {7} - 7 1 + 3 + 3 + 7 + 3 + 3 + 7 + 1 + 7 + 7 =
12 min read
Divide and Conquer definition & meaning in DSA
Divide and Conquer is a type of algorithm which involves breaking down a difficult problem into smaller subproblems, solving the subproblems individually and then merging the solutions of those subproblems to solve the actual problem. Properties of Divide and Conquer:Divides the problem into smaller subproblems.Each subproblem is solved independent
2 min read
Maximum Subarray Sum using Divide and Conquer algorithm
You are given a one dimensional array that may contain both positive and negative integers, find the sum of contiguous subarray of numbers which has the largest sum. For example, if the given array is {-2, -5, 6, -2, -3, 1, 5, -6}, then the maximum subarray sum is 7 (see highlighted elements). Recommended: Please solve it on “PRACTICE ” first, befo
12 min read
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Given two square matrices A and B of size n x n each, find their multiplication matrix. Naive Method: Following is a simple way to multiply two matrices. C/C++ Code void multiply(int A[][N], int B[][N], int C[][N]) { for (int i = 0; i &lt; N; i++) { for (int j = 0; j &lt; N; j++) { C[i][j] = 0; for (int k = 0; k &lt; N; k++) { C[i][j] += A[i][k]*B[
15+ min read
Tiling Problem using Divide and Conquer algorithm
Given a n by n board where n is of form 2k where k &gt;= 1 (Basically n is a power of 2 with minimum value as 2). The board has one missing cell (of size 1 x 1). Fill the board using L shaped tiles. A L shaped tile is a 2 x 2 square with one cell of size 1x1 missing. Figure 1: An example inputThis problem can be solved using Divide and Conquer. Bel
15+ min read
Longest Common Prefix using Divide and Conquer Algorithm
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" We have discussed word by word matching and character by character matching algorithms.In this algorithm, a divide and conquer approach is discussed. We first divide th
7 min read
Convex Hull using Divide and Conquer Algorithm
In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computational geometry for several reasons: Collision detectio
15 min read
Divide and Conquer Algorithm
Divide and Conquer algorithm is a problem-solving strategy that involves breaking down a complex problem into smaller, more manageable parts, solving each part individually, and then combining the solutions to solve the original problem. It is a widely used algorithmic technique in computer science and mathematics. Example: In the Merge Sort algori
4 min read
Divide and Conquer in Python
Divide and Conquer is an effective approach for managing challenges that divides a major problem into smaller, easier-to-manage subproblems. The solution to the main problem is obtained by combining the final solutions from multiple individually solved subproblems. This approach works especially well with issues that naturally break down into diffe
3 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
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
How to Type Dynamic Object with Methods with Dynamic Argument Count ?
We are going to learn about how to type dynamic objects with methods with dynamic argument count. Type dynamic object with methods with dynamic argument count means defining an object in a programming language such as TypeScript or Python, where the methods of the object can accept varying numbers of arguments dynamically at runtime, providing flex
2 min read
Decrease and Conquer
As divide-and-conquer approach is already discussed, which include following steps: Divide the problem into a number of subproblems that are smaller instances of the same problem. Conquer the sub problems by solving them recursively. If the subproblem sizes are small enough, however, just solve the sub problems in a straightforward manner. Combine
5 min read
Transform and Conquer Technique
The Transform and conquer technique is a way of solving problems by breaking them down into smaller subproblems, solving the smaller subproblems, and then combining the solutions to the subproblems to solve the original problem. This technique can be used to solve problems in many different areas, including mathematics, computer science, and engine
5 min read
Problem Reduction in Transform and Conquer Technique
What is Problem Reduction?Problem reduction is an algorithm design technique that takes a complex problem and reduces it to a simpler one. The simpler problem is then solved and the solution of the simpler problem is then transformed to the solution of the original problem. Problem reduction is a powerful technique that can be used to simplify comp
7 min read
Master Theorem For Subtract and Conquer Recurrences
Master theorem is used to determine the Big - O upper bound on functions which possess recurrence, i.e which can be broken into sub problems. Master Theorem For Subtract and Conquer Recurrences: Let T(n) be a function defined on positive n as shown below: for some constants c, a&gt;0, b&gt;0, k&gt;=0 and function f(n). If f(n) is O(nk), then1. If a
3 min read
Representation Change in Transform and Conquer Technique
Representation Change is one of the variants of the Transfer and Conquer technique where the given problem is transformed into another domain that is more familiar or simpler to execute. In the case of representation change, the instance of a given problem is transformed into another representation without affecting the original instance. Character
8 min read
Instance Simplification Method in Transform and Conquer Technique
Instance simplification is one of the Transform and Conquer techniques. To understand Instance Simplification, first let us understand what is transform and conquer. Transform and Conquer is a technique whose main idea is to transfer the problem into some easier or similar versions using some procedure and then solve that easier or simpler versions
9 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
Introduction and Dynamic Programming solution to compute nCr%p
Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is to first compute nCr, then compute nCr % p. This s
15+ min read
Bitmasking and Dynamic Programming | Travelling Salesman Problem
In this post, we will be using our knowledge of dynamic programming and Bitmasking technique to solve one of the famous NP-hard problem "Traveling Salesman Problem".Before solving the problem, we assume that the reader has the knowledge of DP and formation of DP transition relationBitmasking in DPTraveling Salesman problem To understand this concep
15+ min read
three90RightbarBannerImg