InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Longest Common Subsequence

medium Original β†—
Solving tips
  • This is the archetype two-string alignment DP: dp[i][j] = LCS length of text1[:i] and text2[:j] on a prefix grid.
  • On a match take the diagonal plus one (dp[i-1][j-1]+1); on a mismatch take max(dp[i-1][j], dp[i][j-1]) β€” do not use max on a match, which silently drops valid pairings.
  • Empty-prefix row and column are all zeros; target O(m*n) time, O(min(m,n)) space with two rolling rows.
  • Pitfall: confusing subsequence (allows gaps) with substring (contiguous, uses a reset-to-0-on-mismatch recurrence).

Problem

Given two strings text1 and text2, return the length of their longest common subsequence (LCS). A subsequence keeps characters in their original relative order but may skip any number of them (it need not be contiguous). A common subsequence is one that appears in both strings.

If there is no common subsequence, return 0.

Examples

  • text1 = "abcde", text2 = "ace" β†’ 3 β€” "ace" is a subsequence of both.
  • text1 = "abc", text2 = "abc" β†’ 3 β€” identical strings; the whole string is the LCS.
  • text1 = "abc", text2 = "def" β†’ 0 β€” no shared characters at all.

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • Both strings consist of lowercase English letters.

Lengths up to 1000 each mean the expected solution is O(m Γ— n) β€” up to a million cells.

Think about it first

Hint 1 Compare the last characters. If they are equal, that pair can be the tail of the LCS β€” count it and recurse on both shorter prefixes. If they differ, at least one of those two characters is not in the LCS, so try dropping each and keep the better result.
Hint 2 The subproblem is "LCS length of `text1`'s first `i` characters and `text2`'s first `j` characters." Two prefix lengths β†’ a 2-D table `dp[i][j]`.
Hint 3 If `text1[i-1] == text2[j-1]`: `dp[i][j] = 1 + dp[i-1][j-1]`. Otherwise `dp[i][j] = max(dp[i-1][j], dp[i][j-1])`. The row and column for an empty prefix are all zeros.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.