Shortest Common Supersequence
Last Updated :
28 Nov, 2024
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
Similar Reads
String in Data Structure
A 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 immu
3 min read
Introduction to Strings - Data Structure and Algorithm Tutorials
Strings are sequences of characters. The differences between a character array and a string are, a string is terminated with a special character â\0â and strings are typically immutable in most of the programming languages like Java, Python and JavaScript. Below are some examples of strings: "geeks"
7 min read
Applications, Advantages and Disadvantages of String
The String data structure is the backbone of programming languages and the building blocks of communication. String data structures are one of the most fundamental and widely used tools in computer science and programming. They allow for the representation and manipulation of text and character sequ
6 min read
String, Subsequence & Substring
What is a Substring? A substring is a contiguous part of a string, i.e., a string inside another string. In general, for an string of size n, there are n*(n+1)/2 non-empty substrings. For example, Consider the string "geeks", There are 15 non-empty substrings. The subarrays are: g, ge, gee, geek, ge
6 min read
Storage for Strings in C
In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays [GFGTABS] C char str[4] = "GfG"; /*One extra for string terminator*/ /* OR */ char str[4] = {âGâ, âfâ, âGâ, '\0'}; /* '\0' is string terminator */ [/GFGTA
5 min read
Strings in different language
Basic operations on String
Searching For Characters and Substring in a String in Java
Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java. Searching for a Character in a
5 min read
Reverse a String â Complete Tutorial
Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on. Examples: Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G
14 min read
Left Rotation of a String
Given a string s and an integer d, the task is to left rotate the string by d positions. Examples: Input: s = "GeeksforGeeks", d = 2Output: "eksforGeeksGe" Explanation: After the first rotation, string s becomes "eeksforGeeksG" and after the second rotation, it becomes "eksforGeeksGe". Input: s = "q
15+ min read
Sort string of characters
Given a string of lowercase characters from 'a' - 'z'. We need to write a program to print the characters of this string in sorted order. Examples: Input : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss" Naive Approach - O(n Log n) TimeA simple approach is to use sorting algori
5 min read
Frequency of Characters in Alphabetical Order
Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
9 min read
Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
14 min read
C Program to Find the Length of a String
The length of a string is the number of characters in it without including the null character (â\0â). In this article, we will learn how to find the length of a string in C. The easiest way to find the string length is by using strlen() function from the C strings library. Let's take a look at an ex
2 min read
How to insert characters in a string at a certain position?
Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after
7 min read
Check if two strings are same or not
Given two strings, the task is to check if these two strings are identical(same) or not. Consider case sensitivity. Examples: Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Approach - By Using (==) in C++/Python/C#,
7 min read
Concatenating Two Strings in C
Concatenating two strings means appending one string at the end of another string. In this article, we will learn how to concatenate two strings in C. The most straightforward method to concatenate two strings is by using strcat() function. Let's take a look at an example: [GFGTABS] C #include <s
3 min read
Remove all occurrences of a character in a string
Given a string and a character, remove all the occurrences of the character in the string. Examples: Input : s = "geeksforgeeks" c = 'e'Output : s = "gksforgks"Input : s = "geeksforgeeks" c = 'g'Output : s = "eeksforeeks"Input : s = "geeksforgeeks" c = 'k'Output : s = "geesforgees" Using Built-In Me
2 min read
Binary String
Check if all bits can be made same by single flip
Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit. Input: 101Output: YeExplanation: In 101, the 0 can be flipped to make it all 1 Input: 11Output: NoExplanation: No matter whichever digit you flip, you will not get the
5 min read
Number of flips to make binary string alternate | Set 1
Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Examples : Input : str = â001â Output : 1 Minimum number of flips required = 1 We can flip
8 min read
Binary representation of next number
Given a binary string that represents binary representation of positive number n, the task is to find the binary representation of n+1. The binary input may or may not fit in an integer, so we need to return a string. Examples: Input: s = "10011"Output: "10100"Explanation: Here n = (19)10 = (10011)2
6 min read
Min flips of continuous characters to make all characters same in a string
Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input
8 min read
Generate all binary strings without consecutive 1's
Given an integer, K. Generate all binary strings of size k without consecutive 1's. Examples: Input : K = 3 Output : 000 , 001 , 010 , 100 , 101 Input : K = 4 Output :0000 0001 0010 0100 0101 1000 1001 1010Idea behind that is IF string ends with '1' then we put only '0' at the end. IF string ends wi
15 min read
Find i'th Index character in a binary string obtained after n iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes "01" and 1 becomes "10". Find the (based on indexing) index character in the string after the nth iteration. Examples: Input : m = 5, n = 2, i = 3Output : 1Input : m = 3, n = 3, i = 6Output
6 min read
Substring and Subsequence
All substrings of a given String
Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string. Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c" Input : s = "ab"Output : "a", "ab", "b" Input : s = "a"Output : "a" [Expected Approach] - Using Ite
9 min read
Print all subsequences of a string
Given a string, we have to find out all its subsequences of it. A String is said to be a subsequence of another String, if it can be obtained by deleting 0 or more character without changing its order. Examples: Input : abOutput : "", "a", "b", "ab" Input : abcOutput : "", "a", "b", "c", "ab", "ac",
12 min read
Count Distinct Subsequences
Given a string str of length n, your task is to find the count of distinct subsequences of it. Examples: Input: str = "gfg"Output: 7Explanation: The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input: str = "ggg"Output: 4Explanation: The four distinct subsequences are "",
14 min read
Count distinct occurrences as a subsequence
Given two strings pat and txt, where pat is always shorter than txt, count the distinct occurrences of pat as a subsequence in txt. Examples: Input: txt = abba, pat = abaOutput: 2Explanation: pat appears in txt as below three subsequences.[abba], [abba] Input: txt = banana, pat = banOutput: 3Explana
15+ min read
Longest Common Subsequence (LCS)
Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
15+ min read
Shortest Superstring Problem
Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: Input: arr[] = {"geeks", "quiz", "for"}Output: geeksquizforExplanation: "geeksquizfor" contains all the thr
15+ min read
Printing Shortest Common Supersequence
Given two strings s1 and s2, find the shortest string which has both s1 and s2 as its sub-sequences. If multiple shortest super-sequence exists, print any one of them.Examples: Input: s1 = "geek", s2 = "eke"Output: geekeExplanation: String "geeke" has both string "geek" and "eke" as subsequences.Inp
9 min read
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: 5Explanation: String "geeke" has both string "geek" and "eke" as subsequences. Input: s1 = "AGGTAB", s2 = "GXTXAYB"Output: 9Expl
15+ min read
Longest Repeating Subsequence
Given a string s, the task is to find the length of the longest repeating subsequence, such that the two subsequences don't have the same string character at the same position, i.e. any ith character in the two subsequences shouldn't have the same index in the original string. Examples: Input: s= "a
15+ min read
Longest Palindromic Subsequence (LPS)
Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Examples: Input: s = "bbabcbcab"Output: 7Explanation: Subsequence "babcbab" is the longest su
15+ min read
Longest Palindromic Substring
Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring. Examples: Input: s = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "
12 min read
Palindrome
C Program to Check for Palindrome String
A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. The simplest method to check for palindrome string is to reverse the given string and store it in a tem
4 min read
Check if a given string is a rotation of a palindrome
Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
15+ min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Online algorithm for checking palindrome in a stream
Given a stream of characters (characters are received one by one), write a function that prints 'Yes' if a character makes the complete string palindrome, else prints 'No'. Examples: Input: str[] = "abcba"Output: a Yes // "a" is palindrome b No // "ab" is not palindrome c No // "abc" is not palindro
15+ min read
Print all Palindromic Partitions of a String using Bit Manipulation
Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOut
10 min read
Minimum Characters to Add at Front for Palindrome
Given a string s, the task is to find the minimum number of characters to be added to the front of s to make it palindrome. A palindrome string is a sequence of characters that reads the same forward and backward. Examples: Input: s = "abc"Output: 2Explanation: We can make above string palindrome as
12 min read
Make largest palindrome by changing at most K-digits
Given a string containing all digits, we need to convert this string to a palindrome by changing at most K digits. If many solutions are possible then print lexicographically largest one.Examples: Input : str = â43435â k = 3Output : "93939" Explanation:Lexicographically largest palindrome after 3 ch
15 min read
Minimum Deletions to Make a String Palindrome
Given a string s of length n, the task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. Note: The order of characters should be maintained. Examples : Input : s = "aebcbda"Output : 2Explanation: Remove characters 'e' and 'd'. Resul
15+ min read
Minimum insertions to form a palindrome with permutations allowed
Given a string of lowercase letters. Find minimum characters to be inserted in the string so that it can become palindrome. We can change the positions of characters in the string. Examples: Input: geeksforgeeksOutput: 2Explanation: geeksforgeeks can be changed as: geeksroforskeeg or geeksorfroskeeg
5 min read