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.

See it run

Watch a table of two strings fill one cell at a time, a match stepping in from the diagonal and a mismatch taking the better of up and left, then walk back from the corner to spell out the answer.

Operations

Fill the table: ABCDE vs ACE

dp[i][j] is the LCS length of the first i characters of s1 and the first j characters of s2. Row 0 and column 0 are 0 (an empty prefix shares nothing). Every other cell is diagonal + 1 on a match, or max(up, left) on a mismatch. The answer lands in the bottom-right corner.

Step 1 of 18

An empty 6 × 4 table

""ACE
""····
A····
B····
C····
D····
E····

dp[i][j] = LCS of s1[:i] and s2[:j] · answer at dp[5][3]

Rows are the prefixes of s1 = "ABCDE" and columns the prefixes of s2 = "ACE", each starting with the empty prefix "". So the table is (m + 1) \times (n + 1). Cell dp[i][j] will hold the LCS length of s1[:i] and s2[:j].

Step 1: An empty 6 × 4 table

def lcs(s1, s2):    m, n = len(s1), len(s2)    dp = [[0] * (n + 1) for _ in range(m + 1)]   # row 0 and column 0 stay 0    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           # match: diagonal + 1            else:                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])  # skip one: best of up, left    return dp[m][n]
Time
O(m·n)
Space
O(m·n)
table size
(5 + 1) × (3 + 1) = 24
cells computed
m · n = 15
answer
3 (ACE)

Say the recurrence before you code: match means diagonal + 1, mismatch means the better of skipping a character from either string.

In the real world

The same longest common subsequence doing real jobs. Pick one and step through it.

Two six-letter strings whose LCS, ADH, is spread out with gaps in both. The 7 × 7 table and a walk back that meets a tie.

Step 1 of 5

Two strings, gaps in both

""AEDFHR
""0000000
A0······
B0······
C0······
D0······
G0······
H0······

lcs("ABCDGH", "AEDFHR") = ?

A, D and H appear in both strings in the same order, but never next to each other. The table has 7 \times 7 cells including the empty row and column.

Step 1: Two strings, gaps in both

print(lcs("ABCDGH", "AEDFHR"), lcs_string("ABCDGH", "AEDFHR"))   # 3 ADH

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Sizing the table m × n instead of (m + 1) × (n + 1)

    critical

    Without the empty row and column, the first real row has no up or diagonal neighbour, so you either special-case it or read dp[-1], which Python wraps to the last row silently. The extra row and column of zeros are the base case.

    Wrong
    dp = [[0] * n for _ in range(m)]for i in range(m):    for j in range(n):        if s1[i] == s2[j]:            dp[i][j] = dp[i - 1][j - 1] + 1   # i = 0 reads dp[-1]
    Right
    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
  • Comparing s1[i] with s2[j] in a 1-based table

    critical

    Row i of the table stands for the prefix s1[:i], whose last character is s1[i - 1]. Using s1i compares the wrong characters and runs off the end at i = m.

    Wrong
    if s1[i] == s2[j]:          # off by one, IndexError at i = m
    Right
    if s1[i - 1] == s2[j - 1]:  # the last characters of s1[:i] and s2[:j]
  • Taking diagonal + 1 on a mismatch, or max on a match

    major

    On a mismatch the diagonal ignores that one of the two characters might still pair with something earlier; max(up, left) covers both choices. On a match, max(up, left) misses the +1 the pair earns. Mixing them up gives wrong lengths.

    Wrong
    else:    dp[i][j] = dp[i - 1][j - 1]        # loses answers that skip only one side
    Right
    else:    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
  • Building the table with [[0] * (n + 1)] * (m + 1)

    critical

    List multiplication repeats one reference: every row is the same list, so writing one row writes them all.

    Wrong
    dp = [[0] * (n + 1)] * (m + 1)    # m + 1 references to ONE row
    Right
    dp = [[0] * (n + 1) for _ in range(m + 1)]
  • Two rows without a fresh or swapped curr

    major

    If curr is the same list as prev, the left neighbour overwrites the up and diagonal values you still need. Make a new curr per row, or swap two lists and remember curr[0] must be 0.

    Wrong
    prev = curr = [0] * (n + 1)        # one list under two namesfor ch in s1:    for j in range(1, n + 1):        ...
    Right
    prev = [0] * (n + 1)for ch in s1:    curr = [0] * (n + 1)    for j in range(1, n + 1):        ...    prev = curr
  • Returning the corner for longest common substring

    minor

    In the substring table a mismatch resets to 0, so the corner is only the run ending at the last characters. The answer is the largest value anywhere; track it as you fill.

    Wrong
    return dp[m][n]                    # 0 for "ABCXA" vs "ABCX"; the answer is 4
    Right
    best = max(best, dp[i][j])         # inside the match branchreturn best

Interview tips

  • How to explain it

    • dp[i][j] is the LCS of the first i characters of s1 and the first j of s2; row 0 and column 0 are 0.
    • If the last characters match, both are in some LCS: diagonal + 1. If not, at least one is not: max(up, left).
    • O(m·n) time and space; two rows give O(min(m, n)) space for the length; walk back from the corner for the string.
  • Spot it in problems

    • Two sequences and the words common, shared, align, in order, or delete to make equal.
    • Answers like m + n − LCS (shortest supersequence) or m + n − 2·LCS (deletions).
    • One string compared with its reverse: longest palindromic subsequence is LCS(s, reversed s).
  • Memory tricks

    • Match: diagonal plus one. Miss: best of up and left.
    • Common ancestors: the same people in the same order, gaps allowed.
    • Substring resets, subsequence carries.
  • Watch out

    • Table is (m + 1) × (n + 1); compare s1[i - 1] with s2[j - 1].
    • Two rows lose the traceback: keep the full table if you need the string.
    • The LCS string is not unique; the length is.