Longest Common Subsequence

35 min · longestCommonSubsequence()

Two edited versions of a note may share a clear backbone even when words were inserted between its letters. You want the length of that backbone.

Given lowercase strings text1 and text2, return the length of their longest common subsequence. A subsequence keeps characters in their original order but may skip characters between them. A common subsequence must be obtainable from both strings.

Characters don't need to be adjacent. Their left-to-right order is the part you can't change.

Constraints

  • 1 <= text1.length, text2.length <= 500
  • text1 and text2 contain only lowercase English letters.

Hints

Look at the current pair

Compare one position from each string. If the characters match, you can keep that character and move both positions. What choices remain when they differ?

Name the smaller question

Let a state describe the answer for two suffixes, or for two prefixes. Only the two current boundaries matter; the exact characters you skipped earlier don't.

Compress the table

A bottom-up row depends only on the previous row and the cell immediately to its left. Preserve the old diagonal value before overwriting the current cell.

Follow-up

How would you reconstruct one longest common subsequence instead of returning only its length?

Visible cases

Examples

Example 1

ready
Input
text1 = "abcde"
text2 = "ace"
Expected
3
Why
a, c, e stay in order in both strings

Example 2

ready
Input
text1 = "abc"
text2 = "abc"
Expected
3
Why
the entire string is shared

Example 3

ready
Input
text1 = "abc"
text2 = "def"
Expected
0
Why
the strings share no character

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite