Longest Common Subsequence

Medium

Topics
StringDynamic Programming

Given two strings text1 and text2, return the length of their longest common subsequence (characters in order, not necessarily contiguous). Return 0 if none.

Example 1

text1abcde
text2ace
kept in both
The shaded characters read the same left to right in both strings — ace — and they need not be adjacent, which is what separates a subsequence from a substring. The answer is how many there are, 3.
Rows are the two strings; shaded cells are one longest sequence common to both.
Input:  text1 = "abcde", text2 = "ace"
Output: 3

Example 2

text1abc
text2def
The two strings share no character in common order, so the answer is 0.
Input:  text1 = "abc", text2 = "def"
Output: 0

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • Inputs consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Compare the two strings position by position. If the current characters match, the LCS grows by one from the diagonal; otherwise take the best of dropping one character from either string.

Approach

  1. dp[i][j] = LCS length of the first i chars of s and first j of t.
  2. If s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] + 1.
  3. Else dp[i][j] = max(dp[i-1][j], dp[i][j-1]).

Dry Run

s = "abcde"   t = "ace"
dp[i][j] = LCS length of the first i characters of s and the first j of t.
         ""   a   c   e
  ""      0   0   0   0
  a       0   1   1   1
  b       0   1   1   1
  c       0   1   2   2
  d       0   1   2   2
  e       0   1   2   3
answer 3  --  the subsequence "ace"
Three rows do nothing at all. Row b and row d are identical to the rows above
them, because 'b' and 'd' appear nowhere in t, so the mismatch branch just carries
the best-so-far forward. The value only climbs on the diagonal steps at (a,a),
(c,c) and (e,e).
On a match the value comes from dp[i-1][j-1] + 1 -- the DIAGONAL -- because both
characters are consumed by the pairing. Adding 1 to max(dp[i-1][j], dp[i][j-1])
instead lets one character be spent twice: "ba" against "aac" then returns 2 when
the longest common subsequence is just "a".
On a mismatch the two candidates advance the strings independently, which is what
makes this a subsequence problem rather than a substring one. The matched
characters need not be adjacent in either string -- "ace" is spread across
"abcde" -- so neither index is forced to move in lockstep with the other.

Complexity

  • Time — O(m*n): fill the full table.
  • Space — O(m*n): the DP grid (reducible to O(min(m,n))).

Common Pitfalls

  • On a match the value is dp[i-1][j-1] + 1 -- the diagonal. Adding 1 to max(dp[i-1][j], dp[i][j-1]) instead lets the same character be consumed twice and overcounts: ba against aac returns 2 where the longest common subsequence is just a.
  • Subsequence, not substring. The characters need not be adjacent, which is exactly why the mismatch branch may advance either string independently.

Full Solution — all languages

class Solution:
    def longestCommonSubsequence(self, s, t):
        m,n=len(s),len(t)
        dp=[[0]*(n+1) for _ in range(m+1)]
        for i in range(1,m+1):
            for j in range(1,n+1):
                dp[i][j]=dp[i-1][j-1]+1 if s[i-1]==t[j-1] else max(dp[i-1][j],dp[i][j-1])
        return dp[m][n]
SensAI
Beta
Tap the mic to stop voice mode