Skip to content

1092. Shortest Common Supersequence

Description

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.

A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.

 

Example 1:

    Input: str1 = "abac", str2 = "cab"
    Output: "cabac"
    Explanation: 
    str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
    str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
    The answer provided is the shortest such string that satisfies these properties.
  

Example 2:

    Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa"
    Output: "aaaaaaaa"
  

 

Constraints:

  • 1 <= str1.length, str2.length <= 1000
  • str1 and str2 consist of lowercase English letters.

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(mn)
  • Space complexity: O(n)

 

JavaScript

js
/**
 * @param {string} str1
 * @param {string} str2
 * @return {string}
 */
const shortestCommonSupersequence = function (str1, str2) {
  const m = str1.length;
  const n = str2.length;
  const lcs = () => {
    let dp = new Array(n + 1).fill('');
    for (const letter of str1) {
      const nextDp = new Array(n + 1).fill('');
      for (let index = 0; index < n; index++) {
        const previousSub = dp[index + 1];
        const currentSub = nextDp[index];
        nextDp[index + 1] =
          letter === str2[index]
            ? dp[index] + letter
            : previousSub.length > currentSub.length
              ? previousSub
              : currentSub;
      }
      dp = nextDp;
    }
    return dp[n];
  };
  let a = 0;
  let b = 0;
  let result = '';
  for (const letter of lcs()) {
    while (a < m && str1[a] !== letter) {
      result += str1[a];
      a += 1;
    }
    while (b < n && str2[b] !== letter) {
      result += str2[b];
      b += 1;
    }
    a += 1;
    b += 1;
    result += letter;
  }
  return `${result}${str1.slice(a)}${str2.slice(b)}`;
};

Released under the MIT license