Shortest Common Supersequence
Last Updated :
23 Jul, 2025
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.
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++
// 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
// 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
# 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#
// 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
// 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));
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++
// 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
// 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
# 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#
// 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
// 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);
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++
// 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
// 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
# 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#
// 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
// 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);
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++
// 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
// 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
# 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#
// 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
// 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);
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++
// 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;
}
Java
// 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
# 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#
// 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
// 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);
Exercise:
Extend the above program to print shortest super sequence also using function to print LCS.
Please refer Printing Shortest Common Supersequence for solution
Shortest Common Supersequence | DSA Problem
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