JavaScript Program for Printing Shortest Common Supersequence
Last Updated :
19 Jul, 2024
A Shortest Common Supersequence (SCS) is the shortest or smallest string that contains two given strings as a subsequence. It is a minimal combination of characters that includes all elements of both input strings. In this article, we will see different approaches for printing the shortest common supersequence in JavaScript.
Example:
Input: A = "ABAC", B = "CAB"
Output: CABAC
There are two different approaches to printing the Shortest Common Subsequence in JavaScript. Let’s discuss each one of them.
Using Recursive Approach
- Start by handling the base cases. If either of the input strings is empty, return the other string as the SCS.
- Now check if the last characters of both strings are the same. If they are, recursively find the SCS without these characters and append the common character.
- If the last characters are different, explore two possibilities. Find the SCS by removing the last character from one string and then the other. Choose the shorter SCS from these two options.
- Now return the chosen SCS, which is either the one without the last character from the first string or the one without the last character from the second string, depending on which one is shorter.
Example: In this example, we will print the Shortest Common Supersequence using a Recursive approach.
JavaScript
function findShortestCommonSupersequence(str1, str2) {
// If either of the strings is empty,
// return the other string as the result.
if (str1.length === 0) {
return str2;
}
if (str2.length === 0) {
return str1;
}
// Check if the last characters of
// both strings are the same.
if (str1[str1.length - 1] === str2[str2.length - 1]) {
// If they are, recursively find the SCS
// without the last characters and
// append the common character.
return findShortestCommonSupersequence
(str1.slice(0, -1), str2.slice(0, -1))
+ str1[str1.length - 1];
}
// If the last characters are different,
// explore both possibilities and choose
// the shorter one.
const result1 = findShortestCommonSupersequence
(str1.slice(0, -1), str2);
const result2 = findShortestCommonSupersequence
(str1, str2.slice(0, -1));
// Return the result with the shorter length.
return result1.length < result2.length ? result1 +
str1[str1.length - 1] : result2 + str2[str2.length - 1];
}
// Example usage:
const str1 = "ABAC";
const str2 = "CAB";
const shortestCommonSupersequence =
findShortestCommonSupersequence(str1, str2);
console.log(shortestCommonSupersequence);
Time Complexity: O( 2^(m+n))
Space Complexity: O(m + n)
Using Dynamic Programming
- Create a DP Table to keep track of the Shortest Common Supersequence (SCS) lengths. This table will help us solve the subproblems systematically.
- Now fill the table through both input strings, comparing characters along the way. As you do this, update the table to record how the lengths of the SCS change as you move forward.
- Once the SCS table is filled, now backtrack and follow a path through the table that will enable the reconstruction of the SCS.
- Now return your answer.
Example: In this example, we will print Shortest Common Supersequence using DP approach.
JavaScript
function findShortestSuperSequence(str1, str2) {
// Determine the lengths of the input strings
let m = str1.length;
let n = str2.length;
// Create a dynamic programming table
// to store subproblem results
let dpTable = new Array(m + 1).
fill(null).map(() =>
new Array(n + 1).fill(0));
// Fill in the DP table to
// calculate the length of LCS
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (str1[i - 1] === str2[j - 1]) {
dpTable[i][j] = 1 + dpTable[i - 1][j - 1];
} else {
dpTable[i][j] = Math.max(dpTable[i][j - 1],
dpTable[i - 1][j]);
}
}
}
// Initialize pointers and an empty
// string for the supersequence
let i = m;
let j = n;
let supersequence = "";
// Reconstruct the supersequence
while (i > 0 && j > 0) {
if (str1[i - 1] === str2[j - 1]) {
supersequence = str1[i - 1] + supersequence;
i--;
j--;
} else {
if (dpTable[i - 1][j] > dpTable[i][j - 1]) {
supersequence = str1[i - 1] + supersequence;
i--;
} else {
supersequence = str2[j - 1] + supersequence;
j--;
}
}
}
// Add any remaining characters from both strings
while (i > 0) {
supersequence = str1[i - 1] + supersequence;
i--;
}
while (j > 0) {
supersequence = str2[j - 1] + supersequence;
j--;
}
return supersequence;
}
// Example usage:
let str1 = "abac";
let str2 = "cab";
let shortestSuperSequence =
findShortestSuperSequence(str1, str2);
console.log(shortestSuperSequence);
Time Complexity: O(m*n)
Space Complexity: O(m*n)
Iterative Approach Using a Matrix
The iterative matrix approach builds a solution by constructing a table of minimum lengths for supersequences. Starting from the table's bottom-right, it traces back through matching characters or choosing the shorter path, appending characters to build the shortest common supersequence iteratively.
Example:
JavaScript
function shortestCommonSupersequence(str1, str2) {
const m = str1.length;
const n = str2.length;
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
// Fill the dp table
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i === 0) {
dp[i][j] = j;
} else if (j === 0) {
dp[i][j] = i;
} else if (str1[i - 1] === str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1;
}
}
}
// Trace back through the dp table to build the result
let i = m, j = n;
let result = '';
while (i > 0 && j > 0) {
if (str1[i - 1] === str2[j - 1]) {
result = str1[i - 1] + result;
i--;
j--;
} else if (dp[i - 1][j] < dp[i][j - 1]) {
result = str1[i - 1] + result;
i--;
} else {
result = str2[j - 1] + result;
j--;
}
}
// Add remaining characters from str1 and str2
while (i > 0) {
result = str1[i - 1] + result;
i--;
}
while (j > 0) {
result = str2[j - 1] + result;
j--;
}
return result;
}
let str1 = "abac";
let str2 = "cab";
console.log(shortestCommonSupersequence(str1, str2));
Using LCS (Longest Common Subsequence)
- Compute the Longest Common Subsequence (LCS) of the two strings.
- Use the LCS to construct the Shortest Common Supersequence (SCS).
- For each character in the LCS, append the characters from the input strings until the LCS character is reached in both strings.
- Append the remaining characters from both strings after processing the entire LCS.
Example:
JavaScript
function lcs(str1, str2) {
const m = str1.length, n = str2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(''));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (str1[i - 1] === str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + str1[i - 1];
} else {
dp[i][j] = dp[i - 1][j].length > dp[i][j - 1].length ? dp[i - 1][j] : dp[i][j - 1];
}
}
}
return dp[m][n];
}
function shortestCommonSupersequenceLCS(str1, str2) {
const lcsStr = lcs(str1, str2);
let i = 0, j = 0, k = 0;
let result = '';
while (k < lcsStr.length) {
while (str1[i] !== lcsStr[k]) result += str1[i++];
while (str2[j] !== lcsStr[k]) result += str2[j++];
result += lcsStr[k++];
i++;
j++;
}
return result + str1.slice(i) + str2.slice(j);
}
// Example usage:
const str1 = "abac";
const str2 = "cab";
console.log(shortestCommonSupersequenceLCS(str1, str2));
Greedy Approach
The Greedy Approach involves a direct comparison of characters in the given strings and constructing the supersequence step by step by always taking the next character from one of the strings until both strings are fully consumed.
Steps:
- Initialize two pointers for each string.
- Compare characters at the pointers, appending the character to the supersequence and advancing the corresponding pointer.
- If the characters match, append the character and advance both pointers.
- After either pointer reaches the end, append the remaining characters of the other string to the supersequence.
Example: In this example, we will print the Shortest Common Supersequence using a Greedy approach.
JavaScript
function greedyShortestCommonSupersequence(str1, str2) {
let i = 0, j = 0;
let supersequence = '';
while (i < str1.length && j < str2.length) {
if (str1[i] === str2[j]) {
supersequence += str1[i];
i++;
j++;
} else {
supersequence += str1[i] + str2[j];
i++;
j++;
}
}
// Add remaining characters from both strings
if (i < str1.length) {
supersequence += str1.slice(i);
}
if (j < str2.length) {
supersequence += str2.slice(j);
}
return supersequence;
}
const str1 = "abac";
const str2 = "cab";
console.log(greedyShortestCommonSupersequence(str1, str2));
Similar Reads
JavaScript Program to Print all Subsequences of a String
A subsequence is a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. Subsequences of a string can be found with different methods here, we are using the Recursion method, Iteration method and Bit manipulation me
3 min read
JavaScript Program to Find Longest Common Substring Between Two Strings
In this article, we will see how to find the longest common substring between two strings in JavaScript. A substring is a contiguous sequence of characters within a string. It can be obtained by extracting part of the string starting from any position. We are going to write a JavaScript function tha
4 min read
JavaScript Program to Find the Length of Longest Balanced Subsequence
In this article, we are going to learn about the Length of the Longest Balanced Subsequence in JavaScript. The Length of the Longest Balanced Subsequence refers to the maximum number of characters in a string sequence that can form a valid balanced expression, consisting of matching opening and clos
4 min read
JavaScript Program to find the Longest Consecutive Sequence of Numbers in an Array
In this article, we are going to find the longest consecutive sequence of numbers in an array using JavaScript language. We are given an array that consists of integers we need to find the longest subsequence such that elements in the subsequence are consecutive integers, these numbers are in any or
4 min read
Shortest Supersequence by Sequence Reconstruction
Given an array arr[] and a 2D array sequences[], determine if arr is the shortest possible and the only supersequence for the given sequences. A supersequence is a sequence that has all sequences[i] as subsequences. The task is to return true if arr is the only shortest supersequence for sequences,
8 min read
JavaScript Program to Generate Number Sequence
Find the nâth term in the Look-and-say (Or Count and Say) Sequence. The look-and-say sequence is the sequence of the below integers: 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211How is the above sequence generated? nâth term is generated by reading (n-1)âth term.The first term is "1"Second t
4 min read
Javascript Program to Find the Longest Bitonic Subsequence | DP-15
Given an array arr[0 ... n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is con
3 min read
Javascript Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101"
4 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples:Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- âgeeksforgeeksâ and âgeeksâ. What is the longest common prefix in
3 min read
JavaScript Print shortest Path to Print a String on Screen
Given a screen with the English alphabet (A-Z) and a remote control with navigation keys (left, right, up, down), we have to determine the most efficient way to write a string using the remote. Starting from the top-left corner of the screen, we need to move through the alphabet to spell out the ent
3 min read