Article start
DSA Course: Interview Patterns and Problem Solving
Module 8: Dynamic Programming

Longest Common Subsequence: 2D DP Pattern

Compare prefixes of two strings with a reusable transition.

May 29, 2026·25

Learning Outcome

After this lesson, you should be able to define a DP state over two prefixes and reduce memory to two rows.

Problem Statement

Given two strings, return the length of their longest common subsequence.

InputOutputWhy
text1 = "abcde", text2 = "ace"3The common subsequence "ace" has length 3.

Brute Force Approach

Generate every subsequence of both strings and compare them. This is exponential.

Optimized Approach

Use DP over prefixes. If characters match, extend the diagonal state; otherwise take the best from skipping one character.

Exact Pseudocode

prev = array of zeros with length n + 1
for i from 1 to length(text1):
  curr = array of zeros
  for j from 1 to length(text2):
    if text1[i - 1] == text2[j - 1]:
      curr[j] = prev[j - 1] + 1
    else:
      curr[j] = max(prev[j], curr[j - 1])
  prev = curr
return prev[n]

Reference Code

class Solution:
    def longestCommonSubsequence(self, text1, text2):
        n = len(text2)
        prev = [0] * (n + 1)

        for a in text1:
            curr = [0] * (n + 1)
            for j, b in enumerate(text2, 1):
                if a == b:
                    curr[j] = prev[j - 1] + 1
                else:
                    curr[j] = max(prev[j], curr[j - 1])
            prev = curr

        return prev[n]

Sample Dry Run

StepStateResult
a vs acematch abest length becomes 1
b rowno useful matchbest stays 1
c rowmatch c after abest becomes 2
e rowmatch e after acanswer = 3

Complexity

MeasureValueReason
TimeO(m * n)Every pair of prefix positions is evaluated once.
SpaceO(n)Two rows store the previous and current prefix states.

Edge Cases

  • If either string is empty, the answer is 0.
  • Subsequence does not require contiguous characters.
  • Do not confuse this with longest common substring.

Interview Checklist

  • Use diagonal + 1 when characters match.
  • Use max of top and left when they do not match.
  • Keep row order consistent when optimizing space.

FAQs

Why does matching use the diagonal?

A match extends the best answer from both prefixes before these two characters.

Why not use one string only?

The state depends on positions in both strings, so two dimensions are needed conceptually.

What is the core pattern?

Two-string prefix DP.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.