AlgoViz

Longest common subsequence

medium 20 min

Given two strings, find the longest sequence of characters that appears in both in the same order, gaps allowed.

Video lesson · Chapter 1 of 8

The damaged title cards

0:00 / 5:46

Longest common subsequence in 75 seconds

1:23Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Build the table. (m + 1) × (n + 1) cells; row 0 and column 0 are 0 because an empty prefix shares nothing

Understand it

Start here

Two strings, one shared skeleton

The longest common subsequence (LCS) of two strings is the longest sequence of characters that appears in both, in the same order, but not necessarily next to each other. For "ABCDGH" and "AEDFHR" it is "ADH", length 3: A, D and H appear in that order in each string, with other letters in between. Our running example is "ABCDE" and "ACE", whose LCS is "ACE" itself.

  • Recap: dynamic programming

    Split a problem into overlapping subproblems and solve each once. If that is new, read dynamic programming first.

  • Recap: a 2D table

    Unique paths filled a grid where each cell came from the cell above and the cell to the left. LCS adds a third neighbour: the diagonal.

  • The new idea

    A subproblem is a pair of prefixes: the first ii characters of one string and the first jj of the other. That pair is the cell (i,j)(i, j).

Definitions

Subsequence vs substring

SubsequenceSubstring
Rulekeep the order, gaps allowedone unbroken run
From ABCDEFBDF is oneBCD is one, BDF is not
How many (length nn)2n2^n choices of positionsn(n+1)2\frac{n(n+1)}{2} non-empty runs
Common to ABCDE and ACEACE (3)A, C or E (1)
DP rule on a mismatchcarry max(up, left)reset to 0
Every substring is a subsequence, but not the other way round. LCS is about subsequences.

Why brute force has no chance

#subsequences of a length-n string=∑k=0n(nk)=2n\#\text{subsequences of a length-}n\text{ string} = \sum_{k=0}^{n} \binom{n}{k} = 2^n
Each character is either kept or dropped. A 30-character string already has more than a billion subsequences (counting by positions; repeated letters can make some strings equal).

First attempt

Try every subsequence

List the subsequences of the shorter string (length nn), longest first, and test each one against the longer string (length mm) with a single left-to-right scan. The first one that fits is an LCS.

Cost of the brute force

T(m,n)=2n⏟candidates⋅O(m)⏟check each=O(m⋅2n)T(m, n) = \underbrace{2^n}_{\text{candidates}} \cdot \underbrace{O(m)}_{\text{check each}} = O(m \cdot 2^n)
For two 30-character strings that is about 30×10930 \times 10^9 steps. The table below does it in 30×30=90030 \times 30 = 900.
Python
from itertools import combinationsdef is_subsequence(t, s):    it = iter(s)    return all(ch in it for ch in t)       # each 'in' resumes where the last one stoppeddef lcs_brute(s1, s2):    short, long_ = sorted((s1, s2), key=len)    for k in range(len(short), -1, -1):    # longest candidates first        for idx in combinations(range(len(short)), k):            cand = "".join(short[p] for p in idx)            if is_subsequence(cand, long_):                return cand    return ""print(lcs_brute("ABCDE", "ACE"), lcs_brute("ABCDGH", "AEDFHR"))   # ACE ADH
Correct and easy to trust, which makes it a good checker for the fast version. Too slow for anything long.
Edit and run it in your browser

The key idea

Look at the last characters

Let L(i,j)L(i, j) be the LCS length of the first ii characters of s1s_1 and the first jj characters of s2s_2. Compare the last two characters, s1[i-1] and s2[j-1]. Either they are equal, and the pair can end the common subsequence together, or they differ, and at least one of them is not part of it.

The recurrence

dp[i][j]={0i=0 or j=0dp[i−1][j−1]+1s1[i−1]=s2[j−1]max⁡(dp[i−1][j], dp[i][j−1])otherwise\text{dp}[i][j] = \begin{cases} 0 & i = 0 \text{ or } j = 0 \\ \text{dp}[i-1][j-1] + 1 & s_1[i-1] = s_2[j-1] \\ \max\big(\text{dp}[i-1][j],\ \text{dp}[i][j-1]\big) & \text{otherwise} \end{cases}
Match: diagonal plus one. Mismatch: the better of dropping the last character of s1s_1 (up) or of s2s_2 (left). The answer is dp[m][n]\text{dp}[m][n].

Working out one cell

Three neighbours, two rules. Each cell needs only cells above it, to its left, or both.
  • Match: ↖ + 1

    Both characters contribute, so take the answer without either of them, dp[i-1][j-1], and add one.

  • Skip from s1: ↑

    dp[i-1][j] is the best when the last character of s1s_1 is left out.

  • Skip from s2: ←

    dp[i][j-1] is the best when the last character of s2s_2 is left out. On a mismatch, keep the larger of the two.

Why it works

Two cases, both safe

Match case

s1[i−1]=s2[j−1]=x  ⟹  L(i,j)=L(i−1,j−1)+1s_1[i-1] = s_2[j-1] = x \;\Longrightarrow\; L(i, j) = L(i-1, j-1) + 1
Take any LCS ZZ of the two prefixes. If it does not end with this pair of xxs, either append xx (it was unused at the end of both strings) or move its last matched xx to these final positions. Either way some LCS ends with the pair, and what comes before it is an LCS of the shorter prefixes.

Mismatch case

s1[i−1]≠s2[j−1]  ⟹  L(i,j)=max⁡(L(i−1,j), L(i,j−1))s_1[i-1] \ne s_2[j-1] \;\Longrightarrow\; L(i, j) = \max\big(L(i-1, j),\ L(i, j-1)\big)
The last character of an LCS cannot be both s1[i−1]s_1[i-1] and s2[j−1]s_2[j-1], since they differ. So at least one of them is unused and can be dropped without losing anything; we do not know which, so we try both and keep the max.

Overlapping subproblems

Plain recursion repeats itself

Python
def lcs_rec(s1, s2):    def f(i, j):        if i == 0 or j == 0:            return 0        if s1[i - 1] == s2[j - 1]:            return 1 + f(i - 1, j - 1)        return max(f(i - 1, j), f(i, j - 1))    return f(len(s1), len(s2))print(lcs_rec("ABCDE", "ACE"), lcs_rec("ABCDGH", "AEDFHR"))   # 3 3
The recurrence written directly. Right answers, exponential time.
Edit and run it in your browser

Call tree of f(5, 3) for ABCDE and ACE

15 calls for 12 different prefix pairs. The red subtree is f(2, 1) solved a second time. A match makes one call; a mismatch makes two.

The worst case: no common characters

#calls=2(m+nm)−1≈2⋅4nπn(m=n)\#\text{calls} = 2\binom{m+n}{m} - 1 \approx \frac{2 \cdot 4^{n}}{\sqrt{\pi n}} \quad (m = n)
Every call branches twice until one prefix is empty, so the calls trace every path in an m×nm \times n grid, just like brute-force unique paths. Upper bound: O(2m+n)O(2^{m+n}) time, O(m+n)O(m + n) stack.
Strings (no common letter)Plain recursionWith memoTable cells
3 and 3391916
5 and 55035136
8 and 825,73912981
10 and 10369,511201121
12 and 125,408,311289169
Memoised calls are 1+2mn1 + 2mn here: each inner state is computed once and makes two calls.

Top-down vs bottom-up

Memo vs tabulation

A memoised call

Each of the m⋅nm \cdot n inner states reaches the bottom boxes at most once, so the total work is O(m⋅n)O(m \cdot n).
Python
from functools import cachedef lcs_memo(s1, s2):    @cache    def f(i, j):        if i == 0 or j == 0:            return 0        if s1[i - 1] == s2[j - 1]:            return 1 + f(i - 1, j - 1)        return max(f(i - 1, j), f(i, j - 1))    return f(len(s1), len(s2))print(lcs_memo("ABCDE", "ACE"), lcs_memo("A" * 10, "B" * 10))   # 3 0
The same recursion with functools.cache. Only the states that are actually asked for get computed.
Edit and run it in your browser
Memoisation (top-down)Tabulation (bottom-up)
Howrecursion + cache by (i,j)(i, j)loops fill dp[i][j] row by row
Cells computedonly those reachable from (m,n)(m, n)all m⋅nm \cdot n
Time / spaceO(m⋅n)O(m \cdot n) / O(m⋅n)O(m \cdot n) + stackO(m⋅n)O(m \cdot n) / O(m⋅n)O(m \cdot n)
Recursion depthup to m+nm + n: RecursionError on long stringsnone
Space trickhardeasy: keep two rows
Write whichever you can explain best; interviewers usually want to see the table.

The table

Fill it cell by cell

The bottom-up recipe
  1. 1Create table(m + 1) × (n + 1) zeros
  2. 2Base casesrow 0, column 0 stay 0
  3. 3Fillmatch ↖ + 1, else max(↑, ←)
  4. 4Answerdp[m][n], then trace back
""ACE
""0000
A01 ↖11
B0111
C012 ↖2
D0122
E0123 ↖
ABCDE down the side, ACE across the top. Bold cells are matches that came from the diagonal; every other cell copied the larger of up and left.
Python
def lcs(s1, s2):    m, n = len(s1), len(s2)    dp = [[0] * (n + 1) for _ in range(m + 1)]    for i in range(1, m + 1):        for j in range(1, n + 1):            if s1[i - 1] == s2[j - 1]:                dp[i][j] = dp[i - 1][j - 1] + 1            else:                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])    return dp[m][n]print(lcs("ABCDE", "ACE"), lcs("ABCDGH", "AEDFHR"), lcs("abc", "def"))   # 3 3 0
The standard solution: O(m⋅n)O(m \cdot n) time and space, no recursion.
Edit and run it in your browser

Reconstruction

Trace back the actual subsequence

The corner only says how long the LCS is. To get the letters, start at (m,n)(m, n) and retrace the decisions: on a match the character is in the answer and we step diagonally; on a mismatch we step to whichever neighbour the value was copied from. Characters come out backwards, so reverse at the end. For ABCDE and ACE the walk is (5,3)→(4,2)→(3,2)→(2,1)→(1,1)→(0,0)(5,3) \to (4,2) \to (3,2) \to (2,1) \to (1,1) \to (0,0), collecting E, C, A.

One step of the walk back

At most m+nm + n steps, since each one lowers ii, jj or both. It needs the full table.
Python
def lcs_string(s1, s2):    m, n = len(s1), len(s2)    dp = [[0] * (n + 1) for _ in range(m + 1)]    for i in range(1, m + 1):        for j in range(1, n + 1):            if s1[i - 1] == s2[j - 1]:                dp[i][j] = dp[i - 1][j - 1] + 1            else:                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])    out, i, j = [], m, n    while i > 0 and j > 0:        if s1[i - 1] == s2[j - 1]:            out.append(s1[i - 1])            i, j = i - 1, j - 1        elif dp[i - 1][j] >= dp[i][j - 1]:            i -= 1        else:            j -= 1    return "".join(reversed(out))print(lcs_string("ABCDE", "ACE"), lcs_string("ABCDGH", "AEDFHR"), lcs_string("AGCAT", "GAC"))   # ACE ADH AC
Build the table, then walk back from the corner.
Edit and run it in your browser

Complexity

O(m·n) time, two rows for space

Cost of the table

T(m,n)=m⋅n⏟cells⋅O(1)=O(m⋅n),S(m,n)=O(m⋅n)  →  O(min⁡(m,n))T(m, n) = \underbrace{m \cdot n}_{\text{cells}} \cdot O(1) = O(m \cdot n), \qquad S(m, n) = O(m \cdot n) \;\to\; O(\min(m, n))
Each cell reads three neighbours and does one comparison. Row ii reads only row i−1i - 1 and itself, so two rows along the shorter string are enough for the length.
Python
def lcs_two_rows(s1, s2):    if len(s2) > len(s1):        s1, s2 = s2, s1                   # columns = the shorter string    n = len(s2)    prev = [0] * (n + 1)    for ch in s1:        curr = [0] * (n + 1)        for j in range(1, n + 1):            if ch == s2[j - 1]:                curr[j] = prev[j - 1] + 1          # diagonal is in prev            else:                curr[j] = max(prev[j], curr[j - 1])  # up in prev, left in curr        prev = curr    return prev[n]print(lcs_two_rows("ABCDE", "ACE"), lcs_two_rows("ACE", "ABCDE"))   # 3 3
Two rows: O(m⋅n)O(m \cdot n) time, O(min⁡(m,n))O(\min(m, n)) space. Swap the strings so the columns run along the shorter one.
Edit and run it in your browser
ApproachTimeSpaceGives the string?
Every subsequenceO(m⋅2n)O(m \cdot 2^n)O(n)O(n)Yes
Plain recursionO(2m+n)O(2^{m+n})O(m+n)O(m + n) stackWith extra work
Memoised recursionO(m⋅n)O(m \cdot n)O(m⋅n)O(m \cdot n)Yes, walk the memo
Full tableO(m⋅n)O(m \cdot n)O(m⋅n)O(m \cdot n)Yes, trace back
Two rowsO(m⋅n)O(m \cdot n)O(min⁡(m,n))O(\min(m, n))No (Hirschberg's method can, in linear space)
In an interview: table first, trace back if asked, then offer the two-row version for space.

Siblings

Edit distance, substring and friends

Edit distance (Levenshtein): same table, min instead of max

ed[i][j]={ij=0ji=0ed[i−1][j−1]s1[i−1]=s2[j−1]1+min⁡(ed[i−1][j], ed[i][j−1], ed[i−1][j−1])otherwise\text{ed}[i][j] = \begin{cases} i & j = 0 \\ j & i = 0 \\ \text{ed}[i-1][j-1] & s_1[i-1] = s_2[j-1] \\ 1 + \min\big(\text{ed}[i-1][j],\ \text{ed}[i][j-1],\ \text{ed}[i-1][j-1]\big) & \text{otherwise} \end{cases}
Up is a delete, left is an insert, diagonal is a replace. The base cases are ii and jj, not 0: turning a prefix into the empty string costs one delete per character. kitten → sitting is 3.

Longest common substring: reset instead of carry

sub[i][j]={sub[i−1][j−1]+1s1[i−1]=s2[j−1]0otherwiseanswer=max⁡i,jsub[i][j]\text{sub}[i][j] = \begin{cases} \text{sub}[i-1][j-1] + 1 & s_1[i-1] = s_2[j-1] \\ 0 & \text{otherwise} \end{cases} \qquad \text{answer} = \max_{i,j} \text{sub}[i][j]
A cell is the length of the common run ending at both positions. ABCXA and ABCA have substring 3 (ABC) but subsequence 4 (ABCA).

Which two-string DP is this?

All four fill the same (m+1)×(n+1)(m + 1) \times (n + 1) table in the same order; only the rule per cell changes.
  • Shortest common supersequence

    The shortest string containing both as subsequences has length m+n−Lm + n - L: write the LCS once and every other character once.

  • Delete to make equal

    Deleting characters from both until they match takes m+n−2Lm + n - 2L deletions: everything outside the LCS goes.

  • Longest palindromic subsequence

    It is LCS(s,reverse(s))\text{LCS}(s, \text{reverse}(s)): character gives carac, length 5. See palindromes.

  • Diff tools and DNA

    diff treats lines as characters and shows what is outside the LCS as - and +. Biologists align DNA with a scored version of the same table (Needleman–Wunsch).

Recap

Key takeaways

Key points

  • A subsequence keeps the order and allows gaps; a substring is one unbroken run.
  • Brute force tries all 2^n subsequences of the shorter string: O(m · 2^n).
  • dp[i][j] = LCS of s1[:i] and s2[:j]; the table is (m + 1) × (n + 1) with a row and column of zeros.
  • Match: dp[i-1][j-1] + 1. Mismatch: max(dp[i-1][j], dp[i][j-1]). Answer: dp[m][n].
  • Plain recursion repeats subproblems and is exponential; memo or table gives O(m·n).
  • Walk back from the corner to get the string: diagonal on a match, else towards the larger neighbour.
  • Two rows give O(min(m, n)) space for the length but lose the traceback.
  • Edit distance (min, base cases i and j) and longest common substring (reset to 0) are the same table.

Sources