Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Shortest Common Supersequence Length

Medium · Dynamic Programming · Asked at Amazon, Microsoft, Google

Print the length of the shortest string that has both a and b as subsequences.

Input

Two lines: the strings a and b.

Output

The length of the shortest common supersequence.

Constraints

Characters of a longest common subsequence can be shared; everything else appears once. So the answer is |a| + |b| − LCS(a, b).

Example 1

Input

abac
cab

Output

5

Example 2

Input

geek
eke

Output

5

Hints

  1. Characters of a common subsequence can be written once and serve both strings.
  2. The more you share, the shorter the result — share a longest common subsequence.

Approach

Any common supersequence contains a and b; the characters used by both form a common subsequence, so its length is at least |a| + |b| − LCS. Merging a and b around an LCS achieves exactly that. Compute the LCS with a rolling one-row table.

Complexity: O(|a| · |b|) time · O(|b|) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string a, b;
    cin >> a >> b;
    int n = a.size(), m = b.size();
    vector<int> prev(m + 1, 0), cur(m + 1, 0);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) cur[j] = a[i - 1] == b[j - 1] ? prev[j - 1] + 1 : max(prev[j], cur[j - 1]);
        swap(prev, cur);
    }
    cout << n + m - prev[m] << "\n";
    return 0;
}

Python solution

import sys

a, b = sys.stdin.read().split()[:2]
n, m = len(a), len(b)
prev = [0] * (m + 1)
for i in range(1, n + 1):
    cur = [0] * (m + 1)
    ai = a[i - 1]
    for j in range(1, m + 1):
        if ai == b[j - 1]:
            cur[j] = prev[j - 1] + 1
        else:
            cur[j] = prev[j] if prev[j] > cur[j - 1] else cur[j - 1]
    prev = cur
print(n + m - prev[m])

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String a = br.readLine().trim(), b = br.readLine().trim();
        int n = a.length(), m = b.length();
        int[] prev = new int[m + 1], cur = new int[m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) cur[j] = a.charAt(i - 1) == b.charAt(j - 1) ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
            int[] tmp = prev;
            prev = cur;
            cur = tmp;
        }
        System.out.println(n + m - prev[m]);
    }
}

Solve Shortest Common Supersequence Length online · All practice problems