DSA · Patterns, not puzzles

How do you solve the longest common subsequence problem?

Hardlcsdynamic-programmingstringsUpdated Oct 2026
Quiz this track

Short answer

Build a table where dp[i][j] is the LCS length of the first i characters of one string and the first j of the other. Matching characters extend the diagonal; otherwise take the better of skipping either character.

A subsequence keeps order but does not require contiguity. The two-dimensional state is the pair of prefixes. If the last characters match, they can be part of the answer. If they do not, at least one of them cannot be in the optimal pair, so take the better of dropping either.

js
function longestCommonSubsequence(a, b) {
  const rows = a.length + 1;
  const cols = b.length + 1;
  const dp = Array.from({ length: rows }, () => new Array(cols).fill(0));
  for (let i = 1; i < rows; i++) {
    for (let j = 1; j < cols; j++) {
      if (a[i - 1] === b[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }
  return dp[a.length][b.length];
}
The extra first row and column represent empty prefixes and provide the base cases.

Reading the table

  • A match moves diagonally and adds one
  • A mismatch moves up or left, keeping the larger value
  • The answer is in the bottom-right cell
  • The table uses O(n * m) time and space
  • Only the previous row is needed if you only want the length

To reconstruct the actual subsequence, walk backwards from the bottom-right cell. On a match, prepend the character and move diagonally. Otherwise move toward the larger neighbouring cell. That produces one valid LCS, not necessarily the only one.

LCS is not the same as longest common substring. A substring must be contiguous, which uses a different recurrence and resets to zero on a mismatch.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How do you reconstruct the actual subsequence?
  2. 2How is LCS different from longest common substring?
  3. 3How can you reduce the space to O(min(n, m))?
  4. 4How does LCS relate to edit distance?

Say it in the interview

I use a table indexed by the two prefixes. If the current characters match I extend the diagonal answer by one, otherwise I take the better of dropping a character from either string. The bottom-right cell is the length, and I can reconstruct one subsequence by walking backward from it. The space can be reduced to one row if I only need the length.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.