Shortest Common Supersequence solution explained

Shortest Common Supersequence asks for a shortest string that contains two given strings as subsequences. Its length is len(a) + len(b) - LCS(a, b), because the shared longest common subsequence only needs to be written once. To produce the string, build a table of LCS lengths for every pair of suffixes, then walk both strings from the front: emit a shared character once when they match, and otherwise emit the character whose removal keeps the larger LCS. That takes O(m × n) time and memory for strings of length m and n.

By Published 7 min read

The problem, restated

You get two strings, a and b. Return a string of minimum length that has a as a subsequence and also has b as a subsequence, meaning each can be read out of it left to right by skipping some characters. If several shortest strings exist, any one is accepted.

Examples written for this page (outputs printed by the code below)
abLCS lengthOutput (length)
bricktrick4 (rick)btrick (6)
dataatlas3 (ata)datlas (6)
applepear2applear (7)
nightthing2nthinght (8)
abba1aba (3), and bab is equally short
Examples written for this page (outputs printed by the code below). Scroll sideways on a small screen.

What the interviewer is checking

Interviewers use this problem to see whether you can go from a DP value to a constructed answer. Most candidates know LCS. Fewer can explain why the supersequence length is m + n - LCS, and fewer still can rebuild the string without mixing up indexes. The cleanest presentations state the length formula first, so the interviewer knows you understand the structure, then describe the walk.

Questions worth asking

  • Any shortest answer, or a specific one? Usually any; ask, since it affects tie-breaking.
  • Just the length? If so, LCS alone is enough and you can use one row of memory.
  • Can either string be empty? Then the answer is the other string.

Brute force

A naive search builds candidate strings by merging a and b in every possible interleaving, deciding at each step whether the next character comes from a, from b, or from both when they are equal. There are exponentially many interleavings, and each one that shares a character saves one letter. Picking the shortest result works for tiny inputs and makes the structure visible: the saving is exactly the number of characters written once for both strings, which is where LCS enters.

Why the length is m + n - LCS

In any common supersequence S, mark the positions used to read a and the positions used to read b. Positions used by both carry characters that appear in both strings in the same order, so they form a common subsequence, which has at most LCS(a, b) characters. So S has at least m + n - LCS(a, b) positions. Writing the LCS characters once and slotting every other character of a and b around them reaches that bound.

A suffix LCS table

Define keep[i][j] as the LCS length of a[i:] and b[j:], the suffixes starting at i and j. Fill from the bottom-right corner: if a[i] equals b[j], keep[i][j] = keep[i + 1][j + 1] + 1; otherwise it is the larger of keep[i + 1][j] and keep[i][j + 1]. Building on suffixes rather than prefixes lets the construction walk forward and append characters in order, with no final reversal.

def shortest_supersequence(a, b):
    m, n = len(a), len(b)
    keep = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            if a[i] == b[j]:
                keep[i][j] = keep[i + 1][j + 1] + 1
            else:
                keep[i][j] = max(keep[i + 1][j], keep[i][j + 1])

    parts = []
    i = j = 0
    while i < m and j < n:
        if a[i] == b[j]:
            parts.append(a[i])
            i += 1
            j += 1
        elif keep[i + 1][j] >= keep[i][j + 1]:
            parts.append(a[i])
            i += 1
        else:
            parts.append(b[j])
            j += 1
    return "".join(parts) + a[i:] + b[j:]
Python: suffix table, then a forward walk. O(m * n).
function shortestCommonSupersequence(a, b) {
  const m = a.length;
  const n = b.length;
  const keep = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
  for (let i = m - 1; i >= 0; i--) {
    for (let j = n - 1; j >= 0; j--) {
      keep[i][j] = a[i] === b[j]
        ? keep[i + 1][j + 1] + 1
        : Math.max(keep[i + 1][j], keep[i][j + 1]);
    }
  }
  const parts = [];
  let i = 0;
  let j = 0;
  while (i < m && j < n) {
    if (a[i] === b[j]) {
      parts.push(a[i]);
      i++;
      j++;
    } else if (keep[i + 1][j] >= keep[i][j + 1]) {
      parts.push(a[i++]);
    } else {
      parts.push(b[j++]);
    }
  }
  return parts.join("") + a.slice(i) + b.slice(j);
}
JavaScript: the same table and walk.

Why the walk is optimal

At each step the walk either uses a shared character (when the ends match, taking it together never hurts) or emits one character from a single string. When the characters differ, at least one of them is not part of some longest common subsequence of the remaining suffixes. Moving past the one whose removal keeps the larger keep value preserves the full LCS of what is left, so every LCS character is still written once. The output length is m + n - keep[0][0], the lower bound.

Is matching equal characters greedily always safe? Yes: if a[i] equals b[j], some longest common subsequence of a[i:] and b[j:] starts with that pair, which is why keep[i][j] = keep[i + 1][j + 1] + 1 in that case.

Testing a problem with many right answers

Since "ab" and "ba" have two shortest answers, a test that compares against one fixed string can fail a correct solution. Check properties instead: the output contains a as a subsequence, contains b as a subsequence, and has length m + n - LCS(a, b). That is how this page's code was tested, with the minimum length taken from a separate recursion that never uses LCS.

def is_subsequence(small, big):
    it = iter(big)
    return all(ch in it for ch in small)


def check_supersequence(a, b, s, min_len):
    return is_subsequence(a, s) and is_subsequence(b, s) and len(s) == min_len
Python: the checks used in the tests.

The is_subsequence helper relies on a small Python idiom: "ch in it" advances the iterator until it finds ch, so each character must be found after the previous one.

Complexity

Strings of length m and n
ApproachTimeExtra memory
Try candidate strings by lengthExponentialLarge
Suffix LCS table plus forward walkO(m × n)O(m × n)
Length only, one row of LCSO(m × n)O(min(m, n))
Strings of length m and n. Scroll sideways on a small screen.

Edge cases

  • One string empty: return the other.
  • Equal strings: return either; the walk matches every character.
  • No common characters: the answer is a followed by b (or any interleaving), length m + n.
  • One string a subsequence of the other: return the longer one.

Common mistakes

  • Writing a shared character twice, once for each string.
  • Forgetting to append the leftover tail of whichever string still has characters.
  • Building on a prefix table and walking from the front, which reads the wrong cells. Prefix tables walk backward; suffix tables walk forward.
  • Testing against one expected string when several are correct.
  • Concatenating a and b and removing duplicates, which ignores order.

How to explain it out loud

Fictional example

Length first, then construction
Candidate
The answer must contain both strings. Characters they share in order can be written once, and the most I can share is their LCS. So the length is m plus n minus the LCS.
Candidate
To build it, I make the LCS table on suffixes and walk both strings from the start. If the characters match, I write it once and move both. If not, I write the one whose removal keeps the larger LCS of what remains, and move that pointer.
Interviewer
How would you test it?
Candidate
There can be several correct answers, so I would check that both inputs are subsequences of the output and that its length is m plus n minus the LCS.

Uncrossed Lines is the LCS length on integer arrays, phrased as drawing lines. Stone Game II is a different kind of table, indexed by position and a limit. Longest Common Subsequence covers the base table and its one-row version, and Edit Distance is the other two-string DP that interviewers pair with this one.

Practicing with Natively

Constructing an answer from a table is where most slips happen, so practice narrating the walk one step at a time. In a mock interview on Mac or Windows, Natively transcribes the session, and reading it back shows whether you explained the tie rule. After your own attempt, Natively can read the problem from a screenshot and suggest an approach to compare. More on the AI interview assistant.

Questions people ask

How do you solve Shortest Common Supersequence?

Build an LCS table on suffixes, then walk both strings from the front: write a shared character once when they match, otherwise write the character whose removal keeps the larger LCS of the rest. Append any leftover tail.

Why is the length m + n - LCS?

Positions used by both strings in a supersequence form a common subsequence, so at most LCS characters can be shared. Writing the LCS once and everything else around it reaches that bound.

What is the time complexity?

O(m times n) time and memory to build the string. If only the length is needed, one row of the LCS table suffices.

Is there only one correct answer?

No. For ab and ba, both aba and bab are shortest. Test by checking both inputs are subsequences and the length is m + n - LCS.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP