The Wayback Machine - https://web.archive.org/web/20240726032749/https://www.geeksforgeeks.org/count-common-subsequence-in-two-strings/
Open In App

Count common subsequence in two strings

Last Updated : 08 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given two string S and T. The task is to count the number of the common subsequence in S and T.

Examples:

Input : S = “ajblqcpdz”, T = “aefcnbtdi” 
Output : 11 
Common subsequences are : { “a”, “b”, “c”, “d”, “ab”, “bd”, “ad”, “ac”, “cd”, “abd”, “acd” }

Input : S = “a”, T = “ab” 
Output : 1

To find the number of common subsequences in two string, say S and T, we use Dynamic Programming by defining a 2D array dp[][], where dp[i][j] is the number of common subsequences in the string S[0…i-1] and T[0….j-1]. 

Now, we can define dp[i][j] as = dp[i][j-1] + dp[i-1][j] + 1, when S[i-1] is equal to T[j-1] 
This is because when S[i-1] == S[j-1], using the above fact all the previous common sub-sequences are doubled as they get appended by one more character. Both dp[i][j-1] and dp[i-1][j] contain dp[i-1][j-1] and hence it gets added two times in our recurrence which takes care of doubling of count of all previous common sub-sequences. Addition of 1 in recurrence is for the latest character match : common sub-sequence made up of s1[i-1] and s2[j-1]  = dp[i-1][j] + dp[i][j-1] – dp[i-1][j-1], when S[i-1] is not equal to T[j-1] 
Here we subtract dp[i-1][j-1] once because it is present in both dp[i][j – 1] and dp[i – 1][j] and gets added twice.

Implementation:

C++




// C++ program to count common subsequence in two strings
#include <bits/stdc++.h>
using namespace std;
 
// return the number of common subsequence in
// two strings
int CommonSubsequencesCount(string s, string t)
{
    int n1 = s.length();
    int n2 = t.length();
    int dp[n1+1][n2+1];
 
    for (int i = 0; i <= n1; i++) {
        for (int j = 0; j <= n2; j++) {
            dp[i][j] = 0;
        }
    }
 
    // for each character of S
    for (int i = 1; i <= n1; i++) {
 
        // for each character in T
        for (int j = 1; j <= n2; j++) {
 
            // if character are same in both
            // the string
            if (s[i - 1] == t[j - 1])
                dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j];           
            else
                dp[i][j] = dp[i][j - 1] + dp[i - 1][j] -
                                        dp[i - 1][j - 1];           
        }
    }
 
    return dp[n1][n2];
}
 
// Driver Program
int main()
{
    string s = "ajblqcpdz";
    string t = "aefcnbtdi";
 
    cout << CommonSubsequencesCount(s, t) << endl;
    return 0;
}


Java




// Java program to count common subsequence in two strings
public class GFG {
     
    // return the number of common subsequence in
    // two strings
    static int CommonSubsequencesCount(String s, String t)
    {
        int n1 = s.length();
        int n2 = t.length();
        int dp[][] = new int [n1+1][n2+1];
        char ch1,ch2 ;
       
        for (int i = 0; i <= n1; i++) {
            for (int j = 0; j <= n2; j++) {
                dp[i][j] = 0;
            }
        }
       
        // for each character of S
        for (int i = 1; i <= n1; i++) {
       
            // for each character in T
            for (int j = 1; j <= n2; j++) {
                 
                ch1 = s.charAt(i - 1);
                ch2 = t.charAt(j - 1);
                 
                // if character are same in both 
                // the string                
                if (ch1 == ch2) 
                    dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j];            
                else
                    dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - 
                                            dp[i - 1][j - 1];            
            }
        }
       
        return dp[n1][n2];
    }
    // Driver code
    public static void main (String args[]){
         
          String s = "ajblqcpdz";
          String t = "aefcnbtdi";
           
        System.out.println(CommonSubsequencesCount(s, t));
           
    }
 
// This code is contributed by ANKITRAI1
}


C#




// C# program to count common
// subsequence in two strings
using System;
 
class GFG
{
 
// return the number of common
// subsequence in two strings
static int CommonSubsequencesCount(string s,
                                   string t)
{
    int n1 = s.Length;
    int n2 = t.Length;
    int[,] dp = new int [n1 + 1, n2 + 1];
     
    for (int i = 0; i <= n1; i++)
    {
        for (int j = 0; j <= n2; j++)
        {
            dp[i, j] = 0;
        }
    }
     
    // for each character of S
    for (int i = 1; i <= n1; i++)
    {
     
        // for each character in T
        for (int j = 1; j <= n2; j++)
        {
             
            // if character are same in
            // both the string                
            if (s[i - 1] == t[j - 1])
                dp[i, j] = 1 + dp[i, j - 1] +
                               dp[i - 1, j];            
            else
                dp[i, j] = dp[i, j - 1] +
                           dp[i - 1, j] -
                           dp[i - 1, j - 1];            
        }
    }
     
    return dp[n1, n2];
}
 
// Driver code
public static void Main ()
{
    string s = "ajblqcpdz";
    string t = "aefcnbtdi";
         
    Console.Write(CommonSubsequencesCount(s, t));
}
}
 
// This code is contributed
// by ChitraNayal


Javascript




<script>
 
// Javascript program to count common subsequence in two strings
 
// return the number of common subsequence in
// two strings
function CommonSubsequencesCount(s, t)
{
    var n1 = s.length;
    var n2 = t.length;
    var dp = Array.from(Array(n1+1), ()=> Array(n2+1));
 
    for (var i = 0; i <= n1; i++) {
        for (var j = 0; j <= n2; j++) {
            dp[i][j] = 0;
        }
    }
 
    // for each character of S
    for (var i = 1; i <= n1; i++) {
 
        // for each character in T
        for (var j = 1; j <= n2; j++) {
 
            // if character are same in both
            // the string
            if (s[i - 1] == t[j - 1])
                dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j];           
            else
                dp[i][j] = dp[i][j - 1] + dp[i - 1][j] -
                                        dp[i - 1][j - 1];           
        }
    }
 
    return dp[n1][n2];
}
 
// Driver Program
var s = "ajblqcpdz";
var t = "aefcnbtdi";
document.write( CommonSubsequencesCount(s, t));
 
 
</script>


PHP




<?php
// PHP program to count common subsequence
// in two strings
 
// return the number of common subsequence
// in two strings
function CommonSubsequencesCount($s, $t)
{
    $n1 = strlen($s);
    $n2 = strlen($t);
    $dp = array();
 
    for ($i = 0; $i <= $n1; $i++)
    {
        for ($j = 0; $j <= $n2; $j++)
        {
            $dp[$i][$j] = 0;
        }
    }
 
    // for each character of S
    for ($i = 1; $i <= $n1; $i++)
    {
 
        // for each character in T
        for ($j = 1; $j <= $n2; $j++)
        {
 
            // if character are same in both
            // the string
            if ($s[$i - 1] == $t[$j - 1])
                $dp[$i][$j] = 1 + $dp[$i][$j - 1] +
                                  $dp[$i - 1][$j];    
            else
                $dp[$i][$j] = $dp[$i][$j - 1] +
                              $dp[$i - 1][$j] -
                              $dp[$i - 1][$j - 1];    
        }
    }
 
    return $dp[$n1][$n2];
}
 
// Driver Code
$s = "ajblqcpdz";
$t = "aefcnbtdi";
 
echo CommonSubsequencesCount($s, $t) ."\n";
 
// This code is contributed
// by Akanksha Rai
?>


Python3




# Python3 program to count common
# subsequence in two strings
 
# return the number of common subsequence
# in two strings
def CommonSubsequencesCount(s, t):
 
    n1 = len(s)
    n2 = len(t)
    dp = [[0 for i in range(n2 + 1)]
             for i in range(n1 + 1)]
 
    # for each character of S
    for i in range(1, n1 + 1):
 
        # for each character in T
        for j in range(1, n2 + 1):
 
            # if character are same in both
            # the string
            if (s[i - 1] == t[j - 1]):
                dp[i][j] = (1 + dp[i][j - 1] +
                                dp[i - 1][j])        
            else:
                dp[i][j] = (dp[i][j - 1] + dp[i - 1][j] -
                            dp[i - 1][j - 1])        
         
    return dp[n1][n2]
 
# Driver Code
s = "ajblqcpdz"
t = "aefcnbtdi"
 
print(CommonSubsequencesCount(s, t))
 
# This code is contributed by Mohit Kumar


Output

11




Complexity Analysis:

  • Time Complexity : O(n1 * n2) 
  • Auxiliary Space : O(n1 * n2)

Efficient approach : Space optimization

In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.

Implementation steps:

  • Create a 1D vector prev of size n2+1 and initialize it with 0.
  • Set a base case by initializing the values of prev.
  • Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
  • Now Create a temporary 1d vector curr used to store the current values from previous computations.
  • After every iteration assign the value of curr to prev for further iteration.
  • At last return and print the final answer stored in prev[n2]

Implementation: 
 

C++




// C++ program to count common subsequence in two strings
#include <bits/stdc++.h>
using namespace std;
 
// return the number of common subsequence in
// two strings
int CommonSubsequencesCount(string s, string t)
{
    int n1 = s.length();
    int n2 = t.length();
     
 
    // to store previous computaions of subproblems
    vector<int>prev(n2+1 , 0);
 
 
    // for each character of S
    for (int i = 1; i <= n1; i++) {
        vector<int>curr(n2 +1 , 0);
        // for each character in T
        for (int j = 1; j <= n2; j++) {
 
            // if character are same in both
            // the string
            if (s[i - 1] == t[j - 1])
                curr[j] = 1 + curr[j - 1] + prev[j];       
            else
                curr[j] = curr[j - 1] + prev[j] - prev[j - 1];       
        }
             
        // assigning values
        // for iterate further
        prev = curr;
    }
     
    // return final answer
    return prev[n2];
}
 
// Driver Program
int main()
{
    string s = "ajblqcpdz";
    string t = "aefcnbtdi";
 
    cout << CommonSubsequencesCount(s, t) << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
 
    // Function to count the number of common subsequences in two strings
    public static int CommonSubsequencesCount(String s, String t) {
        int n1 = s.length();
        int n2 = t.length();
 
        // To store previous computations of subproblems
        int[] prev = new int[n2 + 1];
 
        // For each character of S
        for (int i = 1; i <= n1; i++) {
            int[] curr = new int[n2 + 1];
 
            // For each character in T
            for (int j = 1; j <= n2; j++) {
                // If characters are same in both the strings
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    curr[j] = 1 + curr[j - 1] + prev[j];
                } else {
                    curr[j] = curr[j - 1] + prev[j] - prev[j - 1];
                }
            }
 
            // Assigning values for further iterations
            prev = curr;
        }
 
        // Return the final answer
        return prev[n2];
    }
 
    // Driver program
    public static void main(String[] args) {
        String s = "ajblqcpdz";
        String t = "aefcnbtdi";
 
        System.out.println(CommonSubsequencesCount(s, t));
    }
}


C#




using System;
 
public class CommonSubsequenceCount {
    // return the number of common subsequence in
    // two strings
    public static int Count(string s, string t)
    {
        int n1 = s.Length;
        int n2 = t.Length;
 
        // to store previous computations of subproblems
        int[] prev = new int[n2 + 1];
 
        // for each character of S
        for (int i = 1; i <= n1; i++) {
            int[] curr = new int[n2 + 1];
 
            // for each character in T
            for (int j = 1; j <= n2; j++) {
                // if characters are the same in both
                // strings
                if (s[i - 1] == t[j - 1])
                    curr[j] = 1 + curr[j - 1] + prev[j];
                else
                    curr[j] = curr[j - 1] + prev[j]
                              - prev[j - 1];
            }
 
            // assign values for further iteration
            prev = curr;
        }
 
        // return final answer
        return prev[n2];
    }
 
    public static void Main()
    {
        string s = "ajblqcpdz";
        string t = "aefcnbtdi";
 
        Console.WriteLine(Count(s, t));
    }
}


Javascript




// Javascript program to count common subsequence in two strings
 
// return the number of common subsequence in
// two strings
function CommonSubsequencesCount(s, t) {
    let n1 = s.length;
    let n2 = t.length;
     
    // to store previous computaions of subproblems
    let prev = new Array(n2+1).fill(0);
     
    // for each character of s
    for (let i = 1; i <= n1; i++) {
        let curr = new Array(n2 + 1).fill(0);
        // for each character in t
        for (let j = 1; j <= n2; j++) {
            // if character are same in both
            // the string
            if (s[i - 1] === t[j - 1])
                curr[j] = 1 + curr[j - 1] + prev[j];       
            else
                curr[j] = curr[j - 1] + prev[j] - prev[j - 1];       
        }
        // assigning values
        // for iterate further
        prev = curr;
    }
    // return final answer
    return prev[n2];
}
 
// Driver Program
let s = "ajblqcpdz";
let t = "aefcnbtdi";
console.log(CommonSubsequencesCount(s, t));


Python3




def CommonSubsequencesCount(s, t):
    n1 = len(s)
    n2 = len(t)
 
    # to store previous computations of subproblems
    prev = [0] * (n2 + 1)
 
    # for each character of S
    for i in range(1, n1 + 1):
        curr = [0] * (n2 + 1)
        # for each character in T
        for j in range(1, n2 + 1):
            # if characters are the same in both strings
            if s[i - 1] == t[j - 1]:
                curr[j] = 1 + curr[j - 1] + prev[j]
            else:
                curr[j] = curr[j - 1] + prev[j] - prev[j - 1]
        # assigning values for iteration
        prev = curr
     
    # return the final answer
    return prev[n2]
 
# Driver Program
if __name__ == "__main__":
    s = "ajblqcpdz"
    t = "aefcnbtdi"
    print(CommonSubsequencesCount(s, t))


Output

11





Time Complexity : O(n1 * n2) 
Auxiliary Space : O(n2)



Similar Reads

Maximum length subsequence such that adjacent elements in the subsequence have a common factor
Given an array arr[], the task is to find the maximum length of a subsequence such that the adjacent elements in the subsequence have a common factor. Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 } Output: 5Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 } Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 } Output: 6Max length subsequence
9 min read
Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Number of common base strings for two strings
Given two strings s1 and s2, we need to find number of common base strings of two. A substring of a string s is called base string if repeated concatenation of the substring results in s. Examples: Input : s1 = "pqrspqrs" s2 = "pqrspqrspqrspqrs" Output : 2 The two common base strings are "pqrs" and "pqrspqrs". Input: s1 = "bbb" s2 = "bb" Output: 1
6 min read
Longest common anagram subsequence from N strings
Given N strings. Find the longest possible subsequence from each of these N strings such that they are anagram to each other. The task is to print the lexicographically largest subsequence among all the subsequences. Examples: Input: s[] = { geeks, esrka, efrsk } Output: ske First string has "eks", Second string has "esk", third string has "esk". T
11 min read
LCS (Longest Common Subsequence) of three strings
Given 3 strings of all having length &lt; 100,the task is to find the longest common sub-sequence in all three given sequences. Examples: Input : str1 = "geeks" str2 = "geeksfor" str3 = "geeksforgeeks" Output : 5 Longest common subsequence is "geeks" i.e., length = 5 Input : str1 = "abcd1e2" str2 = "bc12ea" str3 = "bd1ea" Output : 3 Longest common
13 min read
Count common characters in two strings
Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.Example Input: s1 = "abcd", s2 = "aad" O
5 min read
Number of triangles formed by joining vertices of n-sided polygon with two common sides and no common sides
Given N-sided polygon we need to find the total number of triangles formed by joining the vertices of the given polygon with exactly two sides being common and no side being common.Examples: Input : N = 6 Output : 6 2 The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The triangle formed has two sides (AB
5 min read
Length of longest common prime subsequence from two given arrays
Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays. Examples: Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8} Output: 4 Explanation: The longest common prime subsequence present in both th
11 min read
Longest Common Subsequence of two arrays out of which one array consists of distinct elements only
Given two arrays firstArr[], consisting of distinct elements only, and secondArr[], the task is to find the length of LCS between these 2 arrays. Examples: Input: firstArr[] = {3, 5, 1, 8}, secondArr[] = {3, 3, 5, 3, 8}Output: 3.Explanation: LCS between these two arrays is {3, 5, 8}. Input : firstArr[] = {1, 2, 1}, secondArr[] = {3}Output: 0 Naive
7 min read
Print all Strings from array A[] having all strings from array B[] as subsequence
Given two arrays A[] and B[] consisting of strings, the task is to print the strings from array A[] having all strings in B[] as a subsequence.Examples: Input: A[] = {"geeksforgeeks", "mapple", "twitter", "table", "Linkedin"}, B[] = {"e", "l"} Output: mapple table linkedin Explanation: Both the strings "e" and "l" are subsets in "mapple", "table",
11 min read
three90RightbarBannerImg