Longest Common Subsequence solution explained

The Longest Common Subsequence of two strings is the longest sequence of characters that appears in both, in the same order, though not necessarily side by side. A table where cell (i, j) holds the answer for the first i characters of one string and the first j of the other solves it in O(m · n) time: matching characters extend the diagonal value by one, otherwise you take the better of the cell above and the cell to the left. Walking the table backward recovers the subsequence itself.

By Published 8 min read

The problem, restated

You have two words. Cross out any letters you like from each, without reordering what is left, so that the two leftovers are identical. What is the longest leftover you can make? That length is the answer. Letters do not have to be adjacent in either word. This is the measure behind many diff tools, which show two files as a long shared sequence of lines plus the insertions and deletions around it.

Examples written for this page
FirstSecondLengthOne longest common subsequence
planetplant5plant
stonelongest3one
catacts2ct or at
oceancanoe3can
abcxyz0Nothing in common
Examples written for this page. Scroll sideways on a small screen.

Subsequence or substring?

Clear this up before writing anything. A substring is contiguous, a subsequence is not. In stone and longest, the longest common substring is just two letters (on or st), while the longest common subsequence is three (o, n, e, with gaps). The two versions use almost the same table but a different rule on a mismatch, and confusing them is the most common way to lose this question. Ask the interviewer which one they mean if the prompt is vague.

What interviewers listen for

LCS is the standard two-sequence dynamic programming problem. The interviewer wants a clear definition of what one cell means, a recurrence justified case by case, correct base cases for empty prefixes, and an honest complexity. Strong candidates also offer to rebuild the actual subsequence and to cut memory, and they can say how LCS relates to edit distance.

Follow-ups

  • Return the subsequence. Keep the full table and walk back from the corner, as shown below.
  • Reduce memory. One row of length min(m, n) + 1, with a saved diagonal.
  • Shortest common supersequence. Its length is m + n minus the LCS length: write both strings and share the common part once.
  • Minimum deletions to make two strings equal. Delete everything outside the LCS: m + n - 2 · LCS.

Brute force

Compare the last characters. If they match, they can both be the final character of a common subsequence, so the answer is one plus the answer for both strings without their last character. If not, at least one of them is unused, so try dropping each in turn and keep the better result. Written as plain recursion this branches twice on every mismatch and is exponential. But there are only (m + 1) · (n + 1) distinct pairs of prefix lengths, which is what the table exploits.

The table

Let dp[i][j] be the LCS length of the first i characters of a and the first j characters of b. Row 0 and column 0 are all zeros, since an empty prefix shares nothing. Every other cell follows the two cases above: a match takes the diagonal plus one, a mismatch takes the larger of above and left.

dp for a = cat (rows) and b = acts (columns)
emptyacts
empty00000
c00111
a01111
t01122
dp for a = cat (rows) and b = acts (columns). Scroll sideways on a small screen.
def lcs_table(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            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])
    return dp


def lcs_string(a, b):
    dp = lcs_table(a, b)
    i, j, picked = len(a), len(b), []
    while i > 0 and j > 0:
        if a[i - 1] == b[j - 1]:
            picked.append(a[i - 1])
            i -= 1
            j -= 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return "".join(reversed(picked))
Python: the full table, then a walk back to rebuild one answer.

The walk back mirrors the recurrence. When the two current characters match, that character is part of the answer and you step diagonally. Otherwise you step toward whichever neighbor holds the larger value, because that is where the current value came from. Ties can go either way and produce different, equally long answers, which is why cat and acts can give ct or at.

Cutting memory to one row

Each cell reads only the row above and the cell to its left, so one row is enough if you are careful about the diagonal. Before overwriting row[j], its old value is the cell above. The diagonal is the old value of row[j - 1], which has already been overwritten by the time you need it, so save it in a variable as you go. Making the shorter string the row keeps memory at O(min(m, n)).

def lcs_length(a, b):
    if len(b) > len(a):
        a, b = b, a  # the row follows the shorter string
    row = [0] * (len(b) + 1)
    for ch in a:
        diagonal = 0  # dp[i - 1][j - 1] for the current j
        for j in range(1, len(b) + 1):
            above = row[j]
            if ch == b[j - 1]:
                row[j] = diagonal + 1
            else:
                row[j] = max(above, row[j - 1])
            diagonal = above
    return row[-1]
Python: one row plus a saved diagonal. O(m · n) time, O(min(m, n)) memory.
function longestCommonSubsequence(a, b) {
  if (b.length > a.length) [a, b] = [b, a];
  const row = new Array(b.length + 1).fill(0);
  for (const ch of a) {
    let diagonal = 0;
    for (let j = 1; j <= b.length; j++) {
      const above = row[j];
      row[j] = ch === b[j - 1] ? diagonal + 1 : Math.max(above, row[j - 1]);
      diagonal = above;
    }
  }
  return row[b.length];
}
JavaScript: the same one-row version.

The trade-off is that one row cannot be walked back, so the subsequence itself is lost. If you need both low memory and the string, Hirschberg's divide-and-conquer method gets there in O(min(m, n)) memory, but naming it is usually enough in an interview.

The contiguous version

For the longest common substring, a mismatch resets the run to zero instead of carrying the best value forward, and the answer is the largest value anywhere in the table rather than the corner.

def longest_common_substring_length(a, b):
    best = 0
    prev = [0] * (len(b) + 1)
    for i in range(1, len(a) + 1):
        cur = [0] * (len(b) + 1)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1] + 1
                best = max(best, cur[j])
        prev = cur
    return best
Python: longest common substring length, for contrast.

Complexity

Strings of length m and n
ApproachTimeExtra memoryCan rebuild the string?
Plain recursionExponentialO(m + n) stackYes
Full tableO(m · n)O(m · n)Yes
One row with saved diagonalO(m · n)O(min(m, n))No
Hirschberg's methodO(m · n)O(min(m, n))Yes
Strings of length m and n. Scroll sideways on a small screen.

Edge cases

  • Either string empty: the answer is 0.
  • Identical strings: the answer is the full length.
  • No shared characters at all: 0.
  • Repeated letters, such as aaab against abaa, where several alignments compete.

Common mistakes

  • Solving the substring problem when the subsequence one was asked, or the other way round.
  • Indexing a[i] instead of a[i - 1] when the table has an extra empty row and column.
  • In the one-row version, reading row[j - 1] as the diagonal after it has been overwritten.
  • On a mismatch, taking the diagonal instead of the best of above and left.
  • Greedily matching the first shared character, which can block a longer alignment later.

How to explain it out loud

Fictional example

Defining the cell, then the cases
Candidate
Quick check: you want a subsequence, so the characters can have gaps? Then I will define cell i, j as the answer for the first i letters of a and the first j letters of b. The empty row and column are zero.
Candidate
If the last letters match, they can be paired, so it is the diagonal plus one. If not, one of them is unused, so I take the larger of the cell above and the cell to the left.
Candidate
That is m times n. If you want the actual letters I keep the whole table and walk back from the corner. If you only need the length, one row and a saved diagonal is enough.

Edit Distance fills the same grid with a minimum and three operations; when only insertions and deletions are allowed, it equals m + n minus twice the LCS. Longest Increasing Subsequence is a one-list relative. Unique Paths is the simplest grid fill if you want to warm up first.

Practicing with Natively

Drawing the small table by hand is what makes LCS click, and you can practice narrating it. Natively on Mac or Windows can read a problem like this from a screenshot during a practice session and suggest how to define the table cell, a useful comparison once you have tried it yourself. Its transcript of your mock shows whether you asked the substring-or-subsequence question. More about the AI interview assistant.

Questions people ask

How do you solve Longest Common Subsequence?

Build a table where cell (i, j) is the answer for the first i characters of one string and the first j of the other. On a match take the diagonal plus one; otherwise take the larger of the cell above and the cell to the left.

What is the time complexity of Longest Common Subsequence?

O(m · n) time for strings of length m and n. The full table uses O(m · n) memory; keeping one row and a saved diagonal cuts it to O(min(m, n)).

What is the difference between longest common subsequence and longest common substring?

A subsequence may skip characters, a substring must be contiguous. In the substring table a mismatch resets the cell to zero and the answer is the largest cell anywhere.

How do you print the longest common subsequence itself?

Keep the full table and start at the bottom-right cell. On matching characters record the character and move diagonally; otherwise move toward the larger of the cell above and the cell to the left. Reverse what you recorded.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP