Count common subsequence in two strings
Last Updated :
08 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:
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
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))
Time Complexity : O(n1 * n2)
Auxiliary Space : O(n2)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly 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
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem