VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-common-subsequence-in-two-strings/

⇱ Count common subsequence in two strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count common subsequence in two strings

Last Updated : 8 Mar, 2024

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:


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: 


Output
11

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

Comment