Educatifu
Open menu

Longest Common Subsequence

Harddynamic-programmingstrings

Find the length of the longest subsequence common to two strings. A subsequence keeps order but may skip characters (it need not be contiguous).

Input

Two lines: the string s, then the string t.

Output

The length of their longest common subsequence.

Examples

Example 1

Input
abcde
ace
Output
3

The subsequence "ace" has length 3.

Example 2

Input
abc
abc
Output
3

Identical strings — length 3.

Example 3

Input
abc
def
Output
0

Nothing in common — 0.

Constraints

  • 0 <= length of s, t <= 1000
  • Both strings consist of lower-case English letters.

Hints

Reveal hint 1

Let dp[i][j] be the LCS length of the first i characters of s and the first j of t.

Reveal hint 2

If s[i-1] == t[j-1] then dp[i][j] = dp[i-1][j-1] + 1; otherwise it is max(dp[i-1][j], dp[i][j-1]).

Reference solution (spoiler — try it yourself first)

Approach

Classic DP grid: extend the diagonal on a character match, otherwise carry the better of dropping one character from either string.

import sys
lines = sys.stdin.read().split('\n')
a = lines[0] if len(lines) > 0 else ''
b = lines[1] if len(lines) > 1 else ''
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
    for j in range(1, n + 1):
        if a[i - 1] == b[j - 1]:
            dp[i][j] = dp[i - 1][j - 1] + 1
        else:
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
print(dp[m][n])

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation