Python coding

Longest shared subsequence

Given two strings a and b, return the length of the longest sequence of characters that appears in both in the same order, though not necessarily side by side. You may delete characters from either string, but never reorder them.

The comparison is case-sensitive. Aim for O(len(a) · len(b)) time.

Besides the tests, one large input (two 12-letter strings) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • shared_subsequence("stone", "longest") → 3
  • shared_subsequence("abcbdab", "bdcaba") → 4
  • shared_subsequence("abc", "def") → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Compare prefixes: let dp[i][j] be the answer for the first i characters of a and the first j of b. Each cell depends on three neighbors.

Hint 2

If a[i-1] == b[j-1], take the diagonal plus one; otherwise the max of the cell above and the cell to the left. Only the previous row is needed.

Solution and why it works
pythonO(m·n), m = len(a), n = len(b) · O(n)
def shared_subsequence(a: str, b: str) -> int:
    prev = [0] * (len(b) + 1)            # previous row: answers for a shorter prefix of a
    for ch in a:
        cur = [0]
        for j, other in enumerate(b, 1):
            if ch == other:
                cur.append(prev[j - 1] + 1)            # match: extend the diagonal
            else:
                cur.append(max(prev[j], cur[j - 1]))   # drop a character from a or from b
        prev = cur
    return prev[-1]

On a match, pairing the two last characters is never worse, so extend the diagonal; on a mismatch, one of them goes unused, so take the better of dropping it from a or from b. That is m × n cells at O(1) each, against exponential recursion. Don't reset to 0 on a mismatch: that computes the longest common substring, which must be contiguous (2 for "stone" and "longest", not 3). One previous row cuts memory to O(n).

Related lab: Big-O growth