Shortest common supersequence
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The shortest common supersequence is the shortest text that contains both given texts as subsequences, so each can be found in it in order. You find what they share, write that once, and add what is left. It is the idea behind merging two lists without repeats.
Practical use cases
- Web app: Merging two to-do lists. A shared task app has two users' lists that both contain some of the same tasks in the same order. Merging them into a single list without duplicates, while keeping each person's order, uses this idea. Both people see one tidy list, and it is as short as possible.
- Web app: Merging offline edits. A note app syncs edits made on a phone and a laptop to the same note. The shared lines are kept once and the different lines from each device are slotted in around them in order. Nothing is lost and nothing is repeated.
- System: DNA assembly and compression. Gene-assembly tools stitch overlapping DNA fragments into the shortest sequence that still contains every fragment. Fragments that share a stretch have it written once, so the result is far shorter than gluing them end to end.
The story: The Shared Shop Board
Zoya and Aarav ran two stalls at the mohalla fair. Zoya's signboard needed the letters A B A C in that order; Aarav's needed C A B. They could only afford one wooden board, so the board's letters had to include both orders, skipping allowed. "Make it as short as you can," said Zoya, "wood is expensive!"
Aarav tried gluing the words end to end: ABACCAB, seven letters. Too long. Zoya said, "Any letters that both signs share in the right order only need to be painted once!" The more they share, the shorter the board. So the first job is exactly the Longest Common Subsequence they had already learned.
Once the table was ready, they walked back from the corner. A matching letter was painted once; a letter that was dropped when moving up (or left) was painted from that word, then. The sign came out as CABAC: five letters and both words appear inside. That is the Shortest Common Supersequence: the LCS table, rebuilt the other way around.
How to spot this problem, and where you need it
You must combine two sequences into one that still contains both in order, without repeating the parts they share.
Signs you need it
- The problem says "shortest string that has both as subsequences", or you need a merged list that respects both orders.
- Simply joining the two lists leaves duplicates and makes the output too long.
- You can already compute what the two have in common in order, and the rest is left over.
Where to use it in a project
- Merging task lists, playlists or checklists from two users or devices.
- Combining two versions of a document or configuration while keeping each version's order.
The solution
Find the longest common subsequence of the two sequences using the usual table. The merged result has a length equal to the sum of both lengths minus the length of the common part. To build it, walk back through the table: when two items match, write it once; otherwise write the item from one sequence and step back in that sequence. Then reverse what you wrote.
Payoff: Before: two lists of 20 items joined into 40 with duplicates. After: a merged list of 28 items if 12 are shared.
Explain it like I am 8
Two friends each want their favourite letters in order on one banner. If both share some letters, you paint those once. The more they have in common, the shorter the banner gets, so you first find the biggest common part.
How it works, step by step
- Build the LCS table for the two words exactly as before.
- The shortest supersequence has
len(a) + len(b) - lcsletters: shared letters count once. - Walk back from the corner. If the letters match, write that letter once and move diagonally.
- If they do not match, write the letter from the side you are leaving (above = a's letter, left = b's letter) and move in the bigger direction.
- When one word runs out, add the rest of the other. Reverse what you wrote, since you were walking backwards.
The code in four languages
PHP
<?php
// Shortest string that contains both $a and $b as subsequences.
function shortestSupersequence(string $a, string $b): string {
$m = strlen($a); $n = strlen($b);
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
for ($i = 1; $i <= $m; $i++) { // ordinary LCS table
for ($j = 1; $j <= $n; $j++) {
$dp[$i][$j] = $a[$i - 1] === $b[$j - 1]
? $dp[$i - 1][$j - 1] + 1
: max($dp[$i - 1][$j], $dp[$i][$j - 1]);
}
}
$i = $m; $j = $n; $out = [];
while ($i > 0 && $j > 0) { // walk back, collecting letters
if ($a[$i - 1] === $b[$j - 1]) { $out[] = $a[$i - 1]; $i--; $j--; } // shared: once
elseif ($dp[$i - 1][$j] >= $dp[$i][$j - 1]) { $out[] = $a[$i - 1]; $i--; } // from a
else { $out[] = $b[$j - 1]; $j--; } // from b
}
while ($i > 0) { $out[] = $a[--$i]; } // leftovers of a
while ($j > 0) { $out[] = $b[--$j]; } // leftovers of b
return implode('', array_reverse($out)); // we walked backwards
}
$s = shortestSupersequence('ABAC', 'CAB');
echo $s, ' ', strlen($s), "\n"; // CABAC 5JavaScript
// Shortest string that contains both a and b as subsequences.
function shortestSupersequence(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) { // ordinary LCS table
for (let j = 1; j <= n; j++) {
dp[i][j] = a[i - 1] === b[j - 1]
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
let i = m, j = n;
const out = [];
while (i > 0 && j > 0) { // walk back, collecting letters
if (a[i - 1] === b[j - 1]) { out.push(a[i - 1]); i--; j--; } // shared: once
else if (dp[i - 1][j] >= dp[i][j - 1]) { out.push(a[i - 1]); i--; } // from a
else { out.push(b[j - 1]); j--; } // from b
}
while (i > 0) out.push(a[--i]); // leftovers of a
while (j > 0) out.push(b[--j]); // leftovers of b
return out.reverse().join(''); // we walked backwards
}
const s = shortestSupersequence('ABAC', 'CAB');
console.log(s + ' ' + s.length); // CABAC 5Java
public class Main {
// Shortest string that contains both a and b as subsequences.
static String shortestSupersequence(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) { // ordinary LCS table
for (int j = 1; j <= n; j++) {
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
int i = m, j = n;
StringBuilder out = new StringBuilder();
while (i > 0 && j > 0) { // walk back, collecting letters
if (a.charAt(i - 1) == b.charAt(j - 1)) { out.append(a.charAt(i - 1)); i--; j--; } // shared: once
else if (dp[i - 1][j] >= dp[i][j - 1]) { out.append(a.charAt(i - 1)); i--; } // from a
else { out.append(b.charAt(j - 1)); j--; } // from b
}
while (i > 0) out.append(a.charAt(--i)); // leftovers of a
while (j > 0) out.append(b.charAt(--j)); // leftovers of b
return out.reverse().toString(); // we walked backwards
}
public static void main(String[] args) {
String s = shortestSupersequence("ABAC", "CAB");
System.out.println(s + " " + s.length()); // CABAC 5
}
}Go
package main
import (
"fmt"
"slices"
)
// Shortest string that contains both a and b as subsequences.
func shortestSupersequence(a, b string) string {
m, n := len(a), len(b)
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
for i := 1; i <= m; i++ { // ordinary LCS table
for j := 1; j <= n; j++ {
if a[i-1] == b[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}
i, j := m, n
var out []byte
for i > 0 && j > 0 { // walk back, collecting letters
if a[i-1] == b[j-1] { // shared: once
out = append(out, a[i-1])
i--
j--
} else if dp[i-1][j] >= dp[i][j-1] { // from a
out = append(out, a[i-1])
i--
} else { // from b
out = append(out, b[j-1])
j--
}
}
for i > 0 { // leftovers of a
i--
out = append(out, a[i])
}
for j > 0 { // leftovers of b
j--
out = append(out, b[j])
}
slices.Reverse(out) // we walked backwards
return string(out)
}
func main() {
s := shortestSupersequence("ABAC", "CAB")
fmt.Println(s, len(s)) // CABAC 5
}Time: O(m × n) · Extra space: O(m × n). Same table as LCS, plus a walk back that takes at most m + n steps.
Watch out for
- Just gluing the two words together. That is a valid supersequence but rarely the shortest.
- Forgetting to reverse the collected letters, since the walk starts from the end.
- Dropping the leftover letters when one word runs out before the other.
Quick check
- How long is the shortest common supersequence of ABAC and CAB?
- 7
- 5
- 4
- Which table do we reuse?
- Edit distance
- Coin change
- Longest common subsequence
- When two letters match during the walk back we...
- Write it once and go diagonally
- Write it twice
- Skip it