Shortest Common Supersequence
Given two strings s1 and s2, the task is to find the length of the shortest string that has both s1 and s2 as subsequences.
Examples:
Input: s1 = "geek", s2 = "eke"
Output: 5
Explanation: String "geeke" has both string "geek" and "eke" as subsequences.Input: s1 = "AGGTAB", s2 = "GXTXAYB"
Output: 9
Explanation: String "AGXGTXAYB" has both string "AGGTAB" and "GXTXAYB" as subsequences.
Table of Content
Using LCS Solution - O(m*n) Time and O(m*n) Space
This problem is closely related to the longest common subsequence problem.
- Find the Longest Common Subsequence (LCS) of two given strings. For example, lcs of "geek" and "eke" is "ek".
- Insert non-lcs characters (in their original order in strings) to the lcs found above, and return the result. So "ek" becomes "geeke" which is shortest common supersequence.
Let us consider another example, s1 = "AGGTAB" and s2 = "GXTXAYB". LCS of s1 and s2 is "GTAB". Once we find LCS, we insert characters of both strings in order and we get "AGXGTXAYB"
How does this work?
We need to find a string that has both strings as subsequences and is the shortest such string. If both strings have all characters different, then result is sum of lengths of two given strings. If there are common characters, then we don't want them multiple times as the task is to minimize length. Therefore, we first find the longest common subsequence, take one occurrence of this subsequence and add extra characters.
Length of the shortest supersequence = (Sum of lengths) - (Length of LCS)
// c++ program to find the length of
// the shortest superstring of s1 and s2
#include <bits/stdc++.h>
using namespace std;
// Returns length of LCS for s1[0..m-1], s2[0..n-1]
int lcs(string &s1, string &s2) {
int m = s1.size();
int n = s2.size();
// Initializing a matrix of size (m+1)*(n+1)
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
// Building dp[m+1][n+1] in bottom-up fashion
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s1[i - 1] == s2[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
// dp[m][n] contains length of LCS for s1[0..m-1]
// and s2[0..n-1]
return dp[m][n];
}
int shortestCommonSupersequence(string &s1, string &s2) {
return s1.size() + s2.size() - lcs(s1, s2);
}
int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
cout << shortestCommonSupersequence(s1, s2) << endl;
return 0;
}
// Java program to find length of
// the shortest supersequence
import java.io.*;
class GfG {
static int shortestCommonSupersequence(String s1,
String s2) {
int m = s1.length();
int n = s2.length();
// find lcs
int l = lcs(s1, s2, m, n);
// Result is sum of input string
// lengths - length of lcs
return (m + n - l);
}
// Returns length of LCS
// for X[0..m - 1], Y[0..n - 1]
static int lcs(String s1, String s2, int m, int n) {
int[][] L = new int[m + 1][n + 1];
int i, j;
// Following steps build L[m + 1][n + 1]
// in bottom up fashion. Note that
// L[i][j] contains length of LCS
// of X[0..i - 1]and Y[0..j - 1]
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (s1.charAt(i - 1)
== s2.charAt(j - 1))
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = Math.max(L[i - 1][j],
L[i][j - 1]);
}
}
// L[m][n] contains length of LCS
// for X[0..n - 1] and Y[0..m - 1]
return L[m][n];
}
public static void main(String args[]) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
System.out.println(
shortestCommonSupersequence(s1, s2));
}
}
# Python program to find length of the
# shortest supersequence of X and Y.
def shortestCommonSupersequence(X, Y):
m = len(X)
n = len(Y)
l = lcs(X, Y, m, n)
# Result is sum of input string
# lengths - length of lcs
return (m + n - l)
def lcs(X, Y, m, n):
L = [[0] * (n + 2) for i in
range(m + 2)]
# Following steps build L[m + 1][n + 1]
# in bottom up fashion. Note that L[i][j]
# contains length of LCS of X[0..i - 1]
# and Y[0..j - 1]
for i in range(m + 1):
for j in range(n + 1):
if (i == 0 or j == 0):
L[i][j] = 0
elif (X[i - 1] == Y[j - 1]):
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j],
L[i][j - 1])
# L[m][n] contains length of
# LCS for X[0..n - 1] and Y[0..m - 1]
return L[m][n]
s1 = "AGGTAB"
s2 = "GXTXAYB"
print(shortestCommonSupersequence(s1, s2))
// C# program to find length of
// the shortest supersequence
using System;
class GfG {
static int shortestCommonSupersequence(String s1,
String s2) {
int m = s1.Length;
int n = s2.Length;
// find lcs
int l = lcs(s1, s2, m, n);
// Result is sum of input string
// lengths - length of lcs
return (m + n - l);
}
// Returns length of LCS for
// X[0..m - 1], Y[0..n - 1]
static int lcs(String s1, String s2, int m, int n) {
int[, ] L = new int[m + 1, n + 1];
int i, j;
// Following steps build L[m + 1][n + 1]
// in bottom up fashion.Note that
// L[i][j] contains length of LCS of
// X[0..i - 1] and Y[0..j - 1]
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i, j] = 0;
else if (s1[i - 1] == s2[j - 1])
L[i, j] = L[i - 1, j - 1] + 1;
else
L[i, j] = Math.Max(L[i - 1, j],
L[i, j - 1]);
}
}
// L[m][n] contains length of LCS
// for X[0..n - 1] and Y[0..m - 1]
return L[m, n];
}
static void Main() {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
Console.WriteLine(
shortestCommonSupersequence(s1, s2));
}
}
// JavaScript program to find length of
// the shortest supersequence
function shortestCommonSupersequence(s1, s2) {
var m = s1.length;
var n = s2.length;
// find lcs
var l = lcs(s1, s2, m, n);
// Result is sum of input string lengths - length of lcs
return (m + n - l);
}
// Returns length of LCS for X[0..m - 1], Y[0..n - 1]
function lcs(s1, s2, m, n) {
var L = Array(m + 1).fill(0).map(
() => Array(n + 1).fill(0));
var i, j;
// Following steps build L[m + 1][n + 1] in bottom-up
// fashion
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i === 0 || j === 0) {
L[i][j] = 0;
}
else if (s1.charAt(i - 1)
=== s2.charAt(j - 1)) {
L[i][j] = L[i - 1][j - 1] + 1;
}
else {
L[i][j]
= Math.max(L[i - 1][j], L[i][j - 1]);
}
}
}
// L[m][n] contains length of LCS for s1[0..n - 1] and
// s2[0..m - 1]
return L[m][n];
}
var s1 = "AGGTAB";
var s2 = "GXTXAYB";
console.log(shortestCommonSupersequence(s1, s2));
Output
9
Further Optimization:
We can use a space optimized version of LCS problem to optimize auxiliary space to O(n)
Using Recursion
The recurrence relation is based on comparing the last characters of the substrings s1[0...m-1] and s2[0...n-1]:
1. If the last characters match (s1[m - 1] == s2[n - 1]):
- The last character of both strings will appear only once in the supersequence.
- We add 1 to the result and reduce both m and n by 1 (move diagonally up-left
- shortestCommonSupersequence(s1,s2,m,n) = 1 + shortestCommonSupersequence(s1,s2,m−1,n−1)
2. If the last characters do not match (s1[m - 1] != s2[n - 1]): We consider two cases:
- Include the last character of s1 and find the supersequence of s1[0...m-2] and s2[0...n-1].
- Include the last character of s2 and find the supersequence of s1[0...m-1] and s2[0...n-2].
Take the minimum of these two results and add 1 (for the included character).
- shortestCommonSupersequence(s1, s2, m, n) = 1 + min(shortestCommonSupersequence(s1, s2, m-1, n), shortestCommonSupersequence(s1, s2, m, n-1))
Base Cases:
The base cases for this recursive function are:
- If m == 0: This means that s1 is empty, so the shortest supersequence is simply the length of s2, which is n.
shortestCommonSupersequence(s1, s2, 0, n) = n- If n == 0: This means that s2 is empty, so the shortest supersequence is simply the length of s1, which is m.
shortestCommonSupersequence(s1, s2, m, 0) = m
// C++ program to find
// length of the shortest supersequence
// using recursion
#include <bits/stdc++.h>
using namespace std;
int superSeqHelper(string &s1, string &s2, int m, int n) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m == 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n == 0)
return m;
// If the last characters of both strings match
// they are part of the shortest supersequence
if (s1[m - 1] == s2[n - 1])
return 1 + superSeqHelper(s1, s2, m - 1, n - 1);
// If the last characters do not match, take the minimum
// of excluding the last character of either s1 or s2,
// and add 1 for the current character in supersequence
return 1 + min(superSeqHelper(s1, s2, m - 1, n),
superSeqHelper(s1, s2, m, n - 1));
}
int shortestCommonSupersequence(string &s1, string &s2) {
return superSeqHelper(s1, s2, s1.size(), s2.size());
}
int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
cout << res << endl;
return 0;
}
// Java program to find
// length of the shortest supersequence
// using recursion
import java.util.*;
class GfG {
static int superSeqHelper(String s1, String s2, int m,
int n) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m == 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n == 0)
return m;
// If the last characters of both strings match
// they are part of the shortest supersequence
if (s1.charAt(m - 1) == s2.charAt(n - 1))
return 1 + superSeqHelper(s1, s2, m - 1, n - 1);
// If the last characters do not match, take the
// minimum of excluding the last character of either
// s1 or s2, and add 1 for the current character in
// supersequence
return 1
+ Math.min(superSeqHelper(s1, s2, m - 1, n),
superSeqHelper(s1, s2, m, n - 1));
}
static int shortestCommonSupersequence(String s1,
String s2) {
return superSeqHelper(s1, s2, s1.length(),
s2.length());
}
public static void main(String[] args) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
System.out.println(res);
}
}
# Python program to find
# length of the shortest supersequence
# using recursion
def superSeqHelper(s1, s2, m, n):
# Base case: if s1 is empty, the supersequence
# length is the length of s2
if m == 0:
return n
# Base case: if s2 is empty, the supersequence
# length is the length of s1
if n == 0:
return m
# If the last characters of both strings match
# they are part of the shortest supersequence
if s1[m - 1] == s2[n - 1]:
return 1 + superSeqHelper(s1, s2, m - 1, n - 1)
# If the last characters do not match, take the minimum
# of excluding the last character of either s1 or s2,
# and add 1 for the current character in supersequence
return 1 + min(superSeqHelper(s1, s2, m - 1, n),
superSeqHelper(s1, s2, m, n - 1))
def shortestCommonSupersequence(s1, s2):
return superSeqHelper(s1, s2, len(s1), len(s2))
s1 = "AGGTAB"
s2 = "GXTXAYB"
res = shortestCommonSupersequence(s1, s2)
print(res)
// C# program to find
// length of the shortest supersequence
// using recursion
using System;
class GfG {
static int SuperSeqHelper(string s1, string s2, int m,
int n) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m == 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n == 0)
return m;
// If the last characters of both strings match
// they are part of the shortest supersequence
if (s1[m - 1] == s2[n - 1])
return 1 + SuperSeqHelper(s1, s2, m - 1, n - 1);
// If the last characters do not match, take the
// minimum of excluding the last character of either
// s1 or s2, and add 1 for the current character in
// supersequence
return 1
+ Math.Min(SuperSeqHelper(s1, s2, m - 1, n),
SuperSeqHelper(s1, s2, m, n - 1));
}
static int ShortestCommonSupersequence(string s1,
string s2) {
return SuperSeqHelper(s1, s2, s1.Length, s2.Length);
}
static void Main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = ShortestCommonSupersequence(s1, s2);
Console.WriteLine(res);
}
}
// JavaScript program to find
// length of the shortest supersequence
// using recursion
function superSeqHelper(s1, s2, m, n) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m === 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n === 0)
return m;
// If the last characters of both strings match
// they are part of the shortest supersequence
if (s1[m - 1] === s2[n - 1]) {
return 1 + superSeqHelper(s1, s2, m - 1, n - 1);
}
// If the last characters do not match, take the minimum
// of excluding the last character of either s1 or s2,
// and add 1 for the current character in supersequence
return 1
+ Math.min(superSeqHelper(s1, s2, m - 1, n),
superSeqHelper(s1, s2, m, n - 1));
}
function shortestCommonSupersequence(s1, s2) {
return superSeqHelper(s1, s2, s1.length, s2.length);
}
const s1 = "AGGTAB";
const s2 = "GXTXAYB";
const res = shortestCommonSupersequence(s1, s2);
console.log(res);
Output
9
Using Top-Down DP (Memoization) - O(m*n) Time and O(m*n) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.
1. Optimal Substructure:
The Shortest Common Supersequence (SCS) problem exhibits optimal substructure, which means the solution to the problem can be derived from the solutions of smaller subproblems. The recurrence relation describes how the optimal solution to a larger subproblem can be built from optimal solutions to smaller subproblems. we can express the recursive relation as follows.
2. Overlapping Subproblems:
The Shortest Common Supersequence (SCS) problem exhibits overlapping subproblems, which means that many subproblems are computed multiple times during the recursive process. As the recursion explores different combinations of characters, the same subproblems are often recalculated multiple times, leading to inefficiency.
We create a 2D array memo of size (m+1) x (n+1) where m is the length of string s1 and n is the length of string s2. The value at memo[i][j] will store the length of the shortest common supersequence for the first i characters of s1 and the first j characters of s2.
// C++ program to find Shortest Common Supersequence using
// memoziation
#include <bits/stdc++.h>
using namespace std;
int superSeqHelper(string &s1, string &s2, int m, int n,
vector<vector<int>> &memo) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m == 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n == 0)
return m;
// If the result has already been computed, return it
if (memo[m][n] != -1)
return memo[m][n];
// If the last characters of both strings match
if (s1[m - 1] == s2[n - 1])
return memo[m][n] = 1 + superSeqHelper(s1, s2, m - 1, n - 1, memo);
// If the last characters do not match, take the
// minimum of excluding the last character
// of either s1 or s2, and add 1 for the current
// character in the supersequence
return memo[m][n] =
1 + min(superSeqHelper(s1, s2, m - 1, n, memo),
superSeqHelper(s1, s2, m, n - 1, memo));
}
int shortestCommonSupersequence(string &s1, string &s2) {
int m = s1.size();
int n = s2.size();
vector<vector<int>> memo(m + 1, vector<int>(n + 1, -1));
return superSeqHelper(s1, s2, m, n, memo);
}
int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
cout << res << endl;
return 0;
}
// Java program to find Shortest Common Supersequence using
// memoization
import java.util.*;
class GfG {
static int superSeqHelper(String s1, String s2,
int m, int n,
int[][] memo) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m == 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n == 0)
return m;
// If the result has already been computed, return
// it
if (memo[m][n] != -1)
return memo[m][n];
// If the last characters of both strings match
if (s1.charAt(m - 1) == s2.charAt(n - 1))
return memo[m][n]
= 1
+ superSeqHelper(s1, s2, m - 1, n - 1,
memo);
// If the last characters do not match, take the
// minimum of excluding the last character of either
// s1 or s2, and add 1 for the current character in
// the supersequence
return memo[m][n]
= 1
+ Math.min(
superSeqHelper(s1, s2, m - 1, n, memo),
superSeqHelper(s1, s2, m, n - 1, memo));
}
static int shortestCommonSupersequence(String s1,
String s2) {
int m = s1.length();
int n = s2.length();
// Initialize the memoization table with -1
int[][] memo = new int[m + 1][n + 1];
// Fill the memoization table with -1
for (int[] row : memo) {
Arrays.fill(row, -1);
}
return superSeqHelper(s1, s2, m, n, memo);
}
public static void main(String[] args) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
System.out.println(res);
}
}
# Python program to find the length of the
# Shortest Common Supersequence using memoization
def superSeqHelper(s1, s2, m, n, memo):
# Base case: if s1 is empty, the
# supersequence length is the length of s2
if m == 0:
return n
# Base case: if s2 is empty, the
# supersequence length is the length of s1
if n == 0:
return m
# If the result has already been computed,
# return it
if memo[m][n] != -1:
return memo[m][n]
# If the last characters of both strings match
if s1[m - 1] == s2[n - 1]:
# Compute and store the result
memo[m][n] = 1 + superSeqHelper(s1, s2, m - 1, n - 1, memo)
return memo[m][n]
# If the last characters do not match, take
# the minimum of excluding the last character
# of either s1 or s2, and add 1 for the current
# character in the supersequence
memo[m][n] = 1 + min(superSeqHelper(s1, s2, m - 1, n, memo),
superSeqHelper(s1, s2, m, n - 1, memo))
return memo[m][n]
def shortestCommonSupersequence(s1, s2):
m = len(s1)
n = len(s2)
# Initialize the memoization table with -1
memo = [[-1 for _ in range(n + 1)] for _ in range(m + 1)]
return superSeqHelper(s1, s2, m, n, memo)
if __name__ == "__main__":
s1 = "AGGTAB"
s2 = "GXTXAYB"
res = shortestCommonSupersequence(s1, s2)
print(res)
// c# program to find the length of the
// Shortest Common Supersequence using memoization
using System;
class GfG {
static int SuperSeqHelper(string s1, string s2, int m,
int n, int[, ] memo) {
// Base case: if s1 is empty, the supersequence
// length is the length of s2
if (m == 0)
return n;
// Base case: if s2 is empty, the supersequence
// length is the length of s1
if (n == 0)
return m;
// If the result has already been computed, return
// it
if (memo[m, n] != -1)
return memo[m, n];
// If the last characters of both strings match
if (s1[m - 1] == s2[n - 1]) {
// Compute and store the result
memo[m, n] = 1
+ SuperSeqHelper(s1, s2, m - 1,
n - 1, memo);
return memo[m, n];
}
// If the last characters do not match, take the
// minimum of
// excluding the last character
// of either s1 or s2, and add 1 for the current
// character in the supersequence
memo[m, n]
= 1
+ Math.Min(
SuperSeqHelper(s1, s2, m - 1, n, memo),
SuperSeqHelper(s1, s2, m, n - 1, memo));
return memo[m, n];
}
static int ShortestCommonSupersequence(string s1,
string s2) {
int m = s1.Length;
int n = s2.Length;
// Initialize the memoization table with -1
int[, ] memo = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
memo[i, j] = -1;
}
}
return SuperSeqHelper(s1, s2, m, n, memo);
}
static void Main(string[] args) {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int result = ShortestCommonSupersequence(s1, s2);
Console.WriteLine(result);
}
}
// JavaScript program to find the length of the
// Shortest Common Supersequence using memoization
function superSeqHelper(s1, s2, m, n, memo) {
// Base case: if s1 is empty, the
// supersequence length is the length of s2
if (m === 0)
return n;
// Base case: if s2 is empty, the
// supersequence length is the length of s1
if (n === 0)
return m;
// If the result has already been computed, return it
if (memo[m][n] !== -1)
return memo[m][n];
// If the last characters of both strings match
if (s1[m - 1] === s2[n - 1]) {
// Compute and store the result
memo[m][n] = 1 + superSeqHelper(s1, s2, m - 1, n - 1, memo);
return memo[m][n];
}
// If the last characters do not match, take the
// minimum of excluding the last character
// of either s1 or s2, and add 1 for the current
// character in the supersequence
memo[m][n] = 1 + Math.min(superSeqHelper(s1, s2, m - 1, n, memo),
superSeqHelper(s1, s2, m, n - 1, memo));
return memo[m][n];
}
function shortestCommonSupersequence(s1, s2) {
const m = s1.length;
const n = s2.length;
// Initialize the memoization table with -1
const memo = Array(m + 1).fill().map(() => Array(n + 1).fill(-1));
return superSeqHelper(s1, s2, m, n, memo);
}
const s1 = "AGGTAB";
const s2 = "GXTXAYB";
const result = shortestCommonSupersequence(s1, s2);
console.log(result);
Output
9
Using Bottom-Up DP (Tabulation) - O(m*n) Time and O(m*n) Space
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner
Create a 2D integer array dp of dimensions (m + 1) x (n + 1), where m and n are the lengths of s1 and s2, respectively. The entry dp[i][j] will represent the length of the Shortest Common Supersequence (SCS) for the substrings s1[0...i-1] and s2[0...j-1].
The dynamic programming relation is as follows:
1. If the characters match (s1[i-1] == s2[j-1]):
This character is included only once in the supersequence, so:
dp[i][j] = 1 + dp[i-1][j-1]2. If the characters do not match (s1[i-1] != s2[j-1]):
we take the minimum of both cases, when the last character is taken from s1 or when the last character is taken from s2.
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])Base Case:
For all i =0 , dp[0][j] = j
For all j=0, dp[i][0] = i
Say the strings are s1 = “geek” and s2 = “eke”, Follow below :
// C++ program to find length of the
// shortest supersequence using tabulation
#include <bits/stdc++.h>
using namespace std;
int shortestCommonSupersequence(string &s1, string &s2) {
int m = s1.size();
int n = s2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
// Fill the first column (if s2 is empty,
// all characters of s1 are needed)
for (int i = 0; i <= m; i++)
dp[i][0] = i;
// Fill the first row (if s1 is empty,
// all characters of s2 are needed)
for (int j = 0; j <= n; j++)
dp[0][j] = j;
// Fill the rest of the dp table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// If characters match, add 1
// to the previous result
if (s1[i - 1] == s2[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
// If characters don't match, take
// the minimum of the two possibilities
else
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
cout << res << endl;
return 0;
}
// Java program to find length of the
// shortest supersequence using tabulation
import java.io.*;
class GfG {
static int shortestCommonSupersequence(String s1,
String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m + 1][n + 1];
// Fill table in bottom up manner
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
// Below steps follow above recurrence
if (i == 0)
dp[i][j] = j;
else if (j == 0)
dp[i][j] = i;
else if (s1.charAt(i - 1)
== s2.charAt(j - 1))
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = 1
+ Math.min(dp[i - 1][j],
dp[i][j - 1]);
}
}
return dp[m][n];
}
public static void main(String args[]) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
System.out.println(res);
}
}
# Python program to find length of the
# shortest supersequence using tabulation
def shortestCommonSupersequence(s1, s2):
m = len(s1)
n = len(s2)
# Initialize a 2D DP array
dp = [[0] * (n + 1) for i in range(m + 1)]
# Fill table in a bottom-up manner
for i in range(m + 1):
for j in range(n + 1):
# If s1 is empty, the supersequence is
# the length of s2
if i == 0:
dp[i][j] = j
# If s2 is empty, the supersequence
# is the length of s1
elif j == 0:
dp[i][j] = i
# If the characters match, no need
# to add extra length
elif s1[i - 1] == s2[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
# If characters do not match, take the
# minimum of including either character
else:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
s1 = "AGGTAB"
s2 = "GXTXAYB"
print(shortestCommonSupersequence(s1, s2))
// C# program to find length of the
// shortest supersequence using tabulation
using System;
class GfG {
static int shortestCommonSupersequence(String s1,
String s2) {
int m = s1.Length;
int n = s2.Length;
int[, ] dp = new int[m + 1, n + 1];
// Fill table in bottom up manner
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
// Below steps follow above
// recurrence
if (i == 0)
dp[i, j] = j;
else if (j == 0)
dp[i, j] = i;
else if (s1[i - 1] == s2[j - 1])
dp[i, j] = 1 + dp[i - 1, j - 1];
else
dp[i, j] = 1
+ Math.Min(dp[i - 1, j],
dp[i, j - 1]);
}
}
return dp[m, n];
}
static void Main() {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res=shortestCommonSupersequence(s1, s2);
Console.WriteLine(res);
}
}
// JavaScript program to find length of the
// shortest supersequence using tabulation
function shortestCommonSupersequence(s1, s2) {
let m = s1.length;
let n = s2.length;
var dp = Array(m + 1).fill(0).map(
() => Array(n + 1).fill(0));
// Fill table in bottom-up manner
for (var i = 0; i <= m; i++) {
for (var j = 0; j <= n; j++) {
// Below steps follow above
// recurrence
if (i === 0) {
dp[i][j] = j;
}
else if (j === 0) {
dp[i][j] = i;
}
else if (s1.charAt(i - 1)
=== s2.charAt(j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else {
dp[i][j] = 1
+ Math.min(dp[i - 1][j],
dp[i][j - 1]);
}
}
}
return dp[m][n];
}
var s1 = "AGGTAB";
var s2 = "GXTXAYB";
var res = shortestCommonSupersequence(s1, s2);
console.log(res);
Output
9
Using Space Optimized DP - O(m*n) Time and O(n) Space
In previous approach of dynamic programming we have derive the relation between states as given below:
if (s1[i-1] == s2[j-1])
dp[i][j]= 1 + dp[i-1][j-1]
else
dp[i][j] = 1+ min(dp[i-1][j],dp[i][j-1])If we observe that for calculating current dp[i][j] state we only need previous row dp[i-1][j-1] and current row dp[i][j-1]. There is no need to store all the previous states.
// C++ program to find length of the
// shortest supersequence using Using Space Optimized
#include <bits/stdc++.h>
using namespace std;
int shortestCommonSupersequence(string &s1, string &s2) {
int m = s1.size();
int n = s2.size();
// Two 1D arrays to store only the
// current and previous rows
vector<int> prev(n + 1, 0), curr(n + 1, 0);
// Fill the first row (if s1 is empty,
// all characters of s2 are needed)
for (int j = 0; j <= n; j++)
prev[j] = j;
for (int i = 1; i <= m; i++) {
// Current row starts with i (if s2 is
// empty, all characters of s1 are needed)
curr[0] = i;
for (int j = 1; j <= n; j++) {
// If characters match, add 1 to
// the previous result
if (s1[i - 1] == s2[j - 1])
curr[j] = 1 + prev[j - 1];
// If characters don't match, take the
// minimum of the two possibilities
else
curr[j] = 1 + min(prev[j], curr[j - 1]);
}
// Move current row to previous for the
// next iteration
prev = curr;
}
return prev[n];
}
int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
cout << res << endl;
return 0;
}
// C++ program to find length of the
// shortest supersequence using Using Space Optimized
import java.util.Arrays;
class GfG {
static int shortestCommonSupersequence(String s1,
String s2) {
int m = s1.length();
int n = s2.length();
// Two 1D arrays to store only the
// current and previous rows
int[] prev = new int[n + 1];
int[] curr = new int[n + 1];
// Fill the first row (if s1 is empty,
// all characters of s2 are needed)
for (int j = 0; j <= n; j++)
prev[j] = j;
for (int i = 1; i <= m; i++) {
// Current row starts with i (if s2 is
// empty, all characters of s1 are needed)
curr[0] = i;
for (int j = 1; j <= n; j++) {
// If characters match, add 1 to
// the previous result
if (s1.charAt(i - 1) == s2.charAt(j - 1))
curr[j] = 1 + prev[j - 1];
// If characters don't match, take the
// minimum of the two possibilities
else
curr[j]
= 1
+ Math.min(prev[j], curr[j - 1]);
}
// Move current row to previous for the
// next iteration
prev = curr.clone();
}
return prev[n];
}
public static void main(String[] args) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res = shortestCommonSupersequence(s1, s2);
System.out.println(res);
}
}
# Python program to find length of the
# shortest supersequence using Using Space Optimized
def shortestCommonSupersequence(s1, s2):
m = len(s1)
n = len(s2)
# Two 1D arrays to store only the
# current and previous rows
prev = [0] * (n + 1)
curr = [0] * (n + 1)
# Fill the first row (if s1 is empty,
# all characters of s2 are needed)
for j in range(n + 1):
prev[j] = j
for i in range(1, m + 1):
# Current row starts with i (if s2 is
# empty, all characters of s1 are needed)
curr[0] = i
for j in range(1, n + 1):
# If characters match, add 1 to the
# previous result
if s1[i - 1] == s2[j - 1]:
curr[j] = 1 + prev[j - 1]
# If characters don't match, take the
# minimum of the two possibilities
else:
curr[j] = 1 + min(prev[j], curr[j - 1])
# Move current row to previous for the next
# iteration
prev = curr[:]
return prev[n]
s1 = "AGGTAB"
s2 = "GXTXAYB"
res = shortestCommonSupersequence(s1, s2)
print(res)
// c# program to find length of the
// shortest supersequence using Using Space Optimized
using System;
class GfG {
static int shortestCommonSupersequence(string s1, string s2) {
int m = s1.Length;
int n = s2.Length;
// Two 1D arrays to store only the
// current and previous rows
int[] prev = new int[n + 1];
int[] curr = new int[n + 1];
// Fill the first row (if s1 is empty,
// all characters of s2 are needed)
for (int j = 0; j <= n; j++)
prev[j] = j;
for (int i = 1; i <= m; i++) {
// Current row starts with i (if s2
// is empty, all characters of s1 are needed)
curr[0] = i;
for (int j = 1; j <= n; j++) {
// If characters match, add 1 to the
// previous result
if (s1[i - 1] == s2[j - 1])
curr[j] = 1 + prev[j - 1];
// If characters don't match, take
// the minimum of the two possibilities
else
curr[j] = 1 + Math.Min(prev[j], curr[j - 1]);
}
// Move current row to previous for the
// next iteration
Array.Copy(curr, prev, n + 1);
}
return prev[n];
}
static void Main(string[] args) {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res=shortestCommonSupersequence(s1, s2);
Console.WriteLine(res);
}
}
// JavaScript program to find length of the
// shortest supersequence using Using Space Optimized
function shortestCommonSupersequence(s1, s2) {
let m = s1.length;
let n = s2.length;
// Two 1D arrays to store only the current
// and previous rows
let prev = new Array(n + 1).fill(0);
let curr = new Array(n + 1).fill(0);
// Fill the first row (if s1 is empty, all
// characters of s2 are needed)
for (let j = 0; j <= n; j++) {
prev[j] = j;
}
for (let i = 1; i <= m; i++) {
// Current row starts with i (if s2 is empty,
// all characters of s1 are needed)
curr[0] = i;
for (let j = 1; j <= n; j++) {
// If characters match, add 1 to the
// previous result
if (s1.charAt(i - 1) === s2.charAt(j - 1)) {
curr[j] = 1 + prev[j - 1];
} else {
// If characters don't match, take the
// minimum of the two possibilities
curr[j] = 1 + Math.min(prev[j], curr[j - 1]);
}
}
// Move current row to previous
// for the next iteration
prev = [...curr];
}
return prev[n];
}
let s1 = "AGGTAB";
let s2 = "GXTXAYB";
let res=shortestCommonSupersequence(s1, s2);
console.log(res);
Output
9
Exercise:
Extend the above program to print shortest super sequence also using function to print LCS.
Please refer Printing Shortest Common Supersequence for solution