Longest Common Subsequence using Dynamic Programming

In this CPP tutorial, we are going to discuss how to find the length of a maximum common subsequence of two strings. Finding the Longest Common Subsequence using Dynamic Programming will be a much better practice for us.

What is Subsequence?

A Sub-sequences is a sequence that appears in same relative order, but not necessarily contiguous.

for example :-  ‘a’, ‘b’, ‘c’, ‘ab’, ‘bc’, ‘abc’ are some Sub-sequence of string “abc”.

Why Dynamic Programming?

We can solve the same problem by simple recursive method but time complexity for this approach is exponential. In the worst case, it will be O ( 2^n ). Instead of calculating for the same sub-problem, again and again, we prefer to use a dynamic programming approach and store the result of every sub-problem which reduces the time complexity into linear.

Algorithm to find Longest Common Subsequence in C++

  • Input two strings S1, S2 of length m and n whose sub-sequence to be found.
  • Now, fill up the table dp[m+1][n+1] in bottom-up manner.
  • If character of both string matches then fill the value in dp[][] table by 1+(dp[][] value in previous diagonal )
dp[i][j] = 1+dp[i-1][j-1]
  •  if character of both strings does not matches then, fill the value in dp[][] table as maximum of left or upper value in dp[][] table.
dp[i][j] = max ( dp[i-1][j], dp[i][j-1] )
  • Now, value in dp[m][n] stores our result for longest common sub-sequence of string S1, S2.

   C++ Code to find the longest common subsequence of two strings


#define for(i,a,b) for(int i=a;i<b;i++)

using namespace std;

typedef long long ll;

      void solve(string s1, string s2, ll m, ll n)
     int dp[m+1][n+1];
               if (i == 0 || j == 0) 
                 dp[i][j] = 0; 
               else if(s1[i-1]==s2[j-1])

   int main()
      string s1,s2;
       ll m,n;






As the longest common sub-sequence among the above two input strings is Codese.

also, learn:

Leave a Reply

Your email address will not be published. Required fields are marked *